flyte 2.0.0b32__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of flyte might be problematic. Click here for more details.

Files changed (204) hide show
  1. flyte/__init__.py +108 -0
  2. flyte/_bin/__init__.py +0 -0
  3. flyte/_bin/debug.py +38 -0
  4. flyte/_bin/runtime.py +195 -0
  5. flyte/_bin/serve.py +178 -0
  6. flyte/_build.py +26 -0
  7. flyte/_cache/__init__.py +12 -0
  8. flyte/_cache/cache.py +147 -0
  9. flyte/_cache/defaults.py +9 -0
  10. flyte/_cache/local_cache.py +216 -0
  11. flyte/_cache/policy_function_body.py +42 -0
  12. flyte/_code_bundle/__init__.py +8 -0
  13. flyte/_code_bundle/_ignore.py +121 -0
  14. flyte/_code_bundle/_packaging.py +218 -0
  15. flyte/_code_bundle/_utils.py +347 -0
  16. flyte/_code_bundle/bundle.py +266 -0
  17. flyte/_constants.py +1 -0
  18. flyte/_context.py +155 -0
  19. flyte/_custom_context.py +73 -0
  20. flyte/_debug/__init__.py +0 -0
  21. flyte/_debug/constants.py +38 -0
  22. flyte/_debug/utils.py +17 -0
  23. flyte/_debug/vscode.py +307 -0
  24. flyte/_deploy.py +408 -0
  25. flyte/_deployer.py +109 -0
  26. flyte/_doc.py +29 -0
  27. flyte/_docstring.py +32 -0
  28. flyte/_environment.py +122 -0
  29. flyte/_excepthook.py +37 -0
  30. flyte/_group.py +32 -0
  31. flyte/_hash.py +8 -0
  32. flyte/_image.py +1055 -0
  33. flyte/_initialize.py +628 -0
  34. flyte/_interface.py +119 -0
  35. flyte/_internal/__init__.py +3 -0
  36. flyte/_internal/controllers/__init__.py +129 -0
  37. flyte/_internal/controllers/_local_controller.py +239 -0
  38. flyte/_internal/controllers/_trace.py +48 -0
  39. flyte/_internal/controllers/remote/__init__.py +58 -0
  40. flyte/_internal/controllers/remote/_action.py +211 -0
  41. flyte/_internal/controllers/remote/_client.py +47 -0
  42. flyte/_internal/controllers/remote/_controller.py +583 -0
  43. flyte/_internal/controllers/remote/_core.py +465 -0
  44. flyte/_internal/controllers/remote/_informer.py +381 -0
  45. flyte/_internal/controllers/remote/_service_protocol.py +50 -0
  46. flyte/_internal/imagebuild/__init__.py +3 -0
  47. flyte/_internal/imagebuild/docker_builder.py +706 -0
  48. flyte/_internal/imagebuild/image_builder.py +277 -0
  49. flyte/_internal/imagebuild/remote_builder.py +386 -0
  50. flyte/_internal/imagebuild/utils.py +78 -0
  51. flyte/_internal/resolvers/__init__.py +0 -0
  52. flyte/_internal/resolvers/_task_module.py +21 -0
  53. flyte/_internal/resolvers/common.py +31 -0
  54. flyte/_internal/resolvers/default.py +28 -0
  55. flyte/_internal/runtime/__init__.py +0 -0
  56. flyte/_internal/runtime/convert.py +486 -0
  57. flyte/_internal/runtime/entrypoints.py +204 -0
  58. flyte/_internal/runtime/io.py +188 -0
  59. flyte/_internal/runtime/resources_serde.py +152 -0
  60. flyte/_internal/runtime/reuse.py +125 -0
  61. flyte/_internal/runtime/rusty.py +193 -0
  62. flyte/_internal/runtime/task_serde.py +362 -0
  63. flyte/_internal/runtime/taskrunner.py +209 -0
  64. flyte/_internal/runtime/trigger_serde.py +160 -0
  65. flyte/_internal/runtime/types_serde.py +54 -0
  66. flyte/_keyring/__init__.py +0 -0
  67. flyte/_keyring/file.py +115 -0
  68. flyte/_logging.py +300 -0
  69. flyte/_map.py +312 -0
  70. flyte/_module.py +72 -0
  71. flyte/_pod.py +30 -0
  72. flyte/_resources.py +473 -0
  73. flyte/_retry.py +32 -0
  74. flyte/_reusable_environment.py +102 -0
  75. flyte/_run.py +724 -0
  76. flyte/_secret.py +96 -0
  77. flyte/_task.py +550 -0
  78. flyte/_task_environment.py +316 -0
  79. flyte/_task_plugins.py +47 -0
  80. flyte/_timeout.py +47 -0
  81. flyte/_tools.py +27 -0
  82. flyte/_trace.py +119 -0
  83. flyte/_trigger.py +1000 -0
  84. flyte/_utils/__init__.py +30 -0
  85. flyte/_utils/asyn.py +121 -0
  86. flyte/_utils/async_cache.py +139 -0
  87. flyte/_utils/coro_management.py +27 -0
  88. flyte/_utils/docker_credentials.py +173 -0
  89. flyte/_utils/file_handling.py +72 -0
  90. flyte/_utils/helpers.py +134 -0
  91. flyte/_utils/lazy_module.py +54 -0
  92. flyte/_utils/module_loader.py +104 -0
  93. flyte/_utils/org_discovery.py +57 -0
  94. flyte/_utils/uv_script_parser.py +49 -0
  95. flyte/_version.py +34 -0
  96. flyte/app/__init__.py +22 -0
  97. flyte/app/_app_environment.py +157 -0
  98. flyte/app/_deploy.py +125 -0
  99. flyte/app/_input.py +160 -0
  100. flyte/app/_runtime/__init__.py +3 -0
  101. flyte/app/_runtime/app_serde.py +347 -0
  102. flyte/app/_types.py +101 -0
  103. flyte/app/extras/__init__.py +3 -0
  104. flyte/app/extras/_fastapi.py +151 -0
  105. flyte/cli/__init__.py +12 -0
  106. flyte/cli/_abort.py +28 -0
  107. flyte/cli/_build.py +114 -0
  108. flyte/cli/_common.py +468 -0
  109. flyte/cli/_create.py +371 -0
  110. flyte/cli/_delete.py +45 -0
  111. flyte/cli/_deploy.py +293 -0
  112. flyte/cli/_gen.py +176 -0
  113. flyte/cli/_get.py +370 -0
  114. flyte/cli/_option.py +33 -0
  115. flyte/cli/_params.py +554 -0
  116. flyte/cli/_plugins.py +209 -0
  117. flyte/cli/_run.py +597 -0
  118. flyte/cli/_serve.py +64 -0
  119. flyte/cli/_update.py +37 -0
  120. flyte/cli/_user.py +17 -0
  121. flyte/cli/main.py +221 -0
  122. flyte/config/__init__.py +3 -0
  123. flyte/config/_config.py +248 -0
  124. flyte/config/_internal.py +73 -0
  125. flyte/config/_reader.py +225 -0
  126. flyte/connectors/__init__.py +11 -0
  127. flyte/connectors/_connector.py +270 -0
  128. flyte/connectors/_server.py +197 -0
  129. flyte/connectors/utils.py +135 -0
  130. flyte/errors.py +243 -0
  131. flyte/extend.py +19 -0
  132. flyte/extras/__init__.py +5 -0
  133. flyte/extras/_container.py +286 -0
  134. flyte/git/__init__.py +3 -0
  135. flyte/git/_config.py +21 -0
  136. flyte/io/__init__.py +29 -0
  137. flyte/io/_dataframe/__init__.py +131 -0
  138. flyte/io/_dataframe/basic_dfs.py +223 -0
  139. flyte/io/_dataframe/dataframe.py +1026 -0
  140. flyte/io/_dir.py +910 -0
  141. flyte/io/_file.py +914 -0
  142. flyte/io/_hashing_io.py +342 -0
  143. flyte/models.py +479 -0
  144. flyte/py.typed +0 -0
  145. flyte/remote/__init__.py +35 -0
  146. flyte/remote/_action.py +738 -0
  147. flyte/remote/_app.py +57 -0
  148. flyte/remote/_client/__init__.py +0 -0
  149. flyte/remote/_client/_protocols.py +189 -0
  150. flyte/remote/_client/auth/__init__.py +12 -0
  151. flyte/remote/_client/auth/_auth_utils.py +14 -0
  152. flyte/remote/_client/auth/_authenticators/__init__.py +0 -0
  153. flyte/remote/_client/auth/_authenticators/base.py +403 -0
  154. flyte/remote/_client/auth/_authenticators/client_credentials.py +73 -0
  155. flyte/remote/_client/auth/_authenticators/device_code.py +117 -0
  156. flyte/remote/_client/auth/_authenticators/external_command.py +79 -0
  157. flyte/remote/_client/auth/_authenticators/factory.py +200 -0
  158. flyte/remote/_client/auth/_authenticators/pkce.py +516 -0
  159. flyte/remote/_client/auth/_channel.py +213 -0
  160. flyte/remote/_client/auth/_client_config.py +85 -0
  161. flyte/remote/_client/auth/_default_html.py +32 -0
  162. flyte/remote/_client/auth/_grpc_utils/__init__.py +0 -0
  163. flyte/remote/_client/auth/_grpc_utils/auth_interceptor.py +288 -0
  164. flyte/remote/_client/auth/_grpc_utils/default_metadata_interceptor.py +151 -0
  165. flyte/remote/_client/auth/_keyring.py +152 -0
  166. flyte/remote/_client/auth/_token_client.py +260 -0
  167. flyte/remote/_client/auth/errors.py +16 -0
  168. flyte/remote/_client/controlplane.py +128 -0
  169. flyte/remote/_common.py +30 -0
  170. flyte/remote/_console.py +19 -0
  171. flyte/remote/_data.py +161 -0
  172. flyte/remote/_logs.py +185 -0
  173. flyte/remote/_project.py +88 -0
  174. flyte/remote/_run.py +386 -0
  175. flyte/remote/_secret.py +142 -0
  176. flyte/remote/_task.py +527 -0
  177. flyte/remote/_trigger.py +306 -0
  178. flyte/remote/_user.py +33 -0
  179. flyte/report/__init__.py +3 -0
  180. flyte/report/_report.py +182 -0
  181. flyte/report/_template.html +124 -0
  182. flyte/storage/__init__.py +36 -0
  183. flyte/storage/_config.py +237 -0
  184. flyte/storage/_parallel_reader.py +274 -0
  185. flyte/storage/_remote_fs.py +34 -0
  186. flyte/storage/_storage.py +456 -0
  187. flyte/storage/_utils.py +5 -0
  188. flyte/syncify/__init__.py +56 -0
  189. flyte/syncify/_api.py +375 -0
  190. flyte/types/__init__.py +52 -0
  191. flyte/types/_interface.py +40 -0
  192. flyte/types/_pickle.py +145 -0
  193. flyte/types/_renderer.py +162 -0
  194. flyte/types/_string_literals.py +119 -0
  195. flyte/types/_type_engine.py +2254 -0
  196. flyte/types/_utils.py +80 -0
  197. flyte-2.0.0b32.data/scripts/debug.py +38 -0
  198. flyte-2.0.0b32.data/scripts/runtime.py +195 -0
  199. flyte-2.0.0b32.dist-info/METADATA +351 -0
  200. flyte-2.0.0b32.dist-info/RECORD +204 -0
  201. flyte-2.0.0b32.dist-info/WHEEL +5 -0
  202. flyte-2.0.0b32.dist-info/entry_points.txt +7 -0
  203. flyte-2.0.0b32.dist-info/licenses/LICENSE +201 -0
  204. flyte-2.0.0b32.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1026 @@
1
+ from __future__ import annotations
2
+
3
+ import _datetime
4
+ import collections
5
+ import types
6
+ import typing
7
+ from abc import ABC, abstractmethod
8
+ from dataclasses import is_dataclass
9
+ from typing import Any, ClassVar, Coroutine, Dict, Generic, List, Optional, Type, Union
10
+
11
+ from flyteidl2.core import literals_pb2, types_pb2
12
+ from fsspec.utils import get_protocol
13
+ from mashumaro.types import SerializableType
14
+ from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, model_serializer, model_validator
15
+ from typing_extensions import Annotated, TypeAlias, get_args, get_origin
16
+
17
+ import flyte.storage as storage
18
+ from flyte._logging import logger
19
+ from flyte._utils import lazy_module
20
+ from flyte._utils.asyn import loop_manager
21
+ from flyte.types import TypeEngine, TypeTransformer, TypeTransformerFailedError
22
+ from flyte.types._renderer import Renderable
23
+ from flyte.types._type_engine import modify_literal_uris
24
+
25
+ MESSAGEPACK = "msgpack"
26
+
27
+
28
+ if typing.TYPE_CHECKING:
29
+ import pandas as pd
30
+ import pyarrow as pa
31
+ else:
32
+ pd = lazy_module("pandas")
33
+ pa = lazy_module("pyarrow")
34
+
35
+ T = typing.TypeVar("T") # DataFrame type or a dataframe type
36
+ DF = typing.TypeVar("DF") # Dataframe type
37
+
38
+ # For specifying the storage formats of DataFrames. It's just a string, nothing fancy.
39
+ DataFrameFormat: TypeAlias = str
40
+
41
+ # Storage formats
42
+ PARQUET: DataFrameFormat = "parquet"
43
+ CSV: DataFrameFormat = "csv"
44
+ GENERIC_FORMAT: DataFrameFormat = ""
45
+ GENERIC_PROTOCOL: str = "generic protocol"
46
+
47
+
48
+ class DataFrame(BaseModel, SerializableType):
49
+ """
50
+ This is the user facing DataFrame class. Please don't confuse it with the literals.StructuredDataset
51
+ class (that is just a model, a Python class representation of the protobuf).
52
+ """
53
+
54
+ uri: typing.Optional[str] = Field(default=None)
55
+ format: typing.Optional[str] = Field(default=GENERIC_FORMAT)
56
+
57
+ model_config = ConfigDict(arbitrary_types_allowed=True)
58
+
59
+ # Private attributes that are not part of the Pydantic model schema
60
+ _raw_df: typing.Optional[typing.Any] = PrivateAttr(default=None)
61
+ _metadata: typing.Optional[literals_pb2.StructuredDatasetMetadata] = PrivateAttr(default=None)
62
+ _literal_sd: Optional[literals_pb2.StructuredDataset] = PrivateAttr(default=None)
63
+ _dataframe_type: Optional[Type[Any]] = PrivateAttr(default=None)
64
+ _already_uploaded: bool = PrivateAttr(default=False)
65
+
66
+ # loop manager is working better than synchronicity for some reason, was getting an error but may be an easy fix
67
+ def _serialize(self) -> Dict[str, Optional[str]]:
68
+ # dataclass case
69
+ lt = TypeEngine.to_literal_type(type(self))
70
+ engine = DataFrameTransformerEngine()
71
+ lv = loop_manager.run_sync(engine.to_literal, self, type(self), lt)
72
+ sd = DataFrame(uri=lv.scalar.structured_dataset.uri)
73
+ sd.format = lv.scalar.structured_dataset.metadata.structured_dataset_type.format
74
+ return {
75
+ "uri": sd.uri,
76
+ "format": sd.format,
77
+ }
78
+
79
+ @classmethod
80
+ def _deserialize(cls, value) -> DataFrame:
81
+ uri = value.get("uri", None)
82
+ format_val = value.get("format", None)
83
+
84
+ if uri is None:
85
+ raise ValueError("DataFrame's uri and file format should not be None")
86
+
87
+ engine = DataFrameTransformerEngine()
88
+ return loop_manager.run_sync(
89
+ engine.to_python_value,
90
+ literals_pb2.Literal(
91
+ scalar=literals_pb2.Scalar(
92
+ structured_dataset=literals_pb2.StructuredDataset(
93
+ metadata=literals_pb2.StructuredDatasetMetadata(
94
+ structured_dataset_type=types_pb2.StructuredDatasetType(format=format_val)
95
+ ),
96
+ uri=uri,
97
+ )
98
+ )
99
+ ),
100
+ cls,
101
+ )
102
+
103
+ @model_serializer
104
+ def serialize_dataframe(self) -> Dict[str, Optional[str]]:
105
+ lt = TypeEngine.to_literal_type(type(self))
106
+ sde = DataFrameTransformerEngine()
107
+ lv = loop_manager.run_sync(sde.to_literal, self, type(self), lt)
108
+ return {
109
+ "uri": lv.scalar.structured_dataset.uri,
110
+ "format": lv.scalar.structured_dataset.metadata.structured_dataset_type.format,
111
+ }
112
+
113
+ @model_validator(mode="after")
114
+ def deserialize_dataframe(self, info) -> DataFrame:
115
+ if info.context is None or info.context.get("deserialize") is not True:
116
+ return self
117
+
118
+ engine = DataFrameTransformerEngine()
119
+ return loop_manager.run_sync(
120
+ engine.to_python_value,
121
+ literals_pb2.Literal(
122
+ scalar=literals_pb2.Scalar(
123
+ structured_dataset=literals_pb2.StructuredDataset(
124
+ metadata=literals_pb2.StructuredDatasetMetadata(
125
+ structured_dataset_type=types_pb2.StructuredDatasetType(format=self.format)
126
+ ),
127
+ uri=self.uri,
128
+ )
129
+ )
130
+ ),
131
+ type(self),
132
+ )
133
+
134
+ @classmethod
135
+ def columns(cls) -> typing.Dict[str, typing.Type]:
136
+ return {}
137
+
138
+ @classmethod
139
+ def column_names(cls) -> typing.List[str]:
140
+ return [k for k, v in cls.columns().items()]
141
+
142
+ @classmethod
143
+ def from_df(
144
+ cls,
145
+ val: typing.Optional[typing.Any] = None,
146
+ uri: typing.Optional[str] = None,
147
+ ) -> DataFrame:
148
+ """
149
+ Wrapper to create a DataFrame from a dataframe.
150
+ The reason this is implemented as a wrapper instead of a full translation invoking
151
+ the type engine and the encoders is because there's too much information in the type
152
+ signature of the task that we don't want the user to have to replicate.
153
+ """
154
+ instance = cls(uri=uri)
155
+ instance._raw_df = val
156
+ return instance
157
+
158
+ @classmethod
159
+ def from_existing_remote(
160
+ cls,
161
+ remote_path: str,
162
+ format: typing.Optional[str] = None,
163
+ **kwargs,
164
+ ) -> "DataFrame":
165
+ """
166
+ Create a DataFrame reference from an existing remote dataframe.
167
+
168
+ Args:
169
+ remote_path: The remote path to the existing dataframe
170
+ format: Format of the stored dataframe
171
+
172
+ Example:
173
+ ```python
174
+ df = DataFrame.from_existing_remote("s3://bucket/data.parquet", format="parquet")
175
+ ```
176
+ """
177
+ return cls(uri=remote_path, format=format or GENERIC_FORMAT, **kwargs)
178
+
179
+ @property
180
+ def val(self) -> Optional[DF]:
181
+ return self._raw_df
182
+
183
+ @property
184
+ def metadata(self) -> Optional[literals_pb2.StructuredDatasetMetadata]:
185
+ return self._metadata
186
+
187
+ @property
188
+ def literal(self) -> Optional[literals_pb2.StructuredDataset]:
189
+ return self._literal_sd
190
+
191
+ def open(self, dataframe_type: Type[DF]):
192
+ """
193
+ Load the handler if needed. For the use case like:
194
+ @task
195
+ def t1(df: DataFrame):
196
+ import pandas as pd
197
+ df.open(pd.DataFrame).all()
198
+
199
+ pandas is imported inside the task, so panda handler won't be loaded during deserialization in type engine.
200
+ """
201
+ from flyte.io._dataframe import lazy_import_dataframe_handler
202
+
203
+ lazy_import_dataframe_handler()
204
+ self._dataframe_type = dataframe_type
205
+ return self
206
+
207
+ async def all(self) -> DF: # type: ignore
208
+ if self._dataframe_type is None:
209
+ raise ValueError("No dataframe type set. Use open() to set the local dataframe type you want to use.")
210
+
211
+ if self.uri is not None and self.val is None:
212
+ expected = TypeEngine.to_literal_type(DataFrame)
213
+ await self._set_literal(expected)
214
+
215
+ return await flyte_dataset_transformer.open_as(self.literal, self._dataframe_type, self.metadata)
216
+
217
+ async def _set_literal(self, expected: types_pb2.LiteralType) -> None:
218
+ """
219
+ Explicitly set the DataFrame Literal to handle the following cases:
220
+
221
+ 1. Read the content from a DataFrame with an uri, for example:
222
+
223
+ @task
224
+ def return_df() -> DataFrame:
225
+ df = DataFrame(uri="s3://my-s3-bucket/s3_flyte_dir/df.parquet", format="parquet")
226
+ df = df.open(pd.DataFrame).all()
227
+ return df
228
+
229
+ For details, please refer to this issue: https://github.com/flyteorg/flyte/issues/5954.
230
+
231
+ 2. Need access to self._literal_sd when converting task output LiteralMap back to flyteidl, please see:
232
+ https://github.com/flyteorg/flytekit/blob/f938661ff8413219d1bea77f6914a58c302d5c6c/flytekit/bin/entrypoint.py#L326
233
+
234
+ For details, please refer to this issue: https://github.com/flyteorg/flyte/issues/5956.
235
+ """
236
+ to_literal = await flyte_dataset_transformer.to_literal(self, DataFrame, expected)
237
+ self._literal_sd = to_literal.scalar.structured_dataset
238
+ if self.metadata is None:
239
+ self._metadata = self._literal_sd.metadata
240
+
241
+ async def set_literal(self, expected: types_pb2.LiteralType) -> None:
242
+ """
243
+ A public wrapper method to set the DataFrame Literal.
244
+
245
+ This method provides external access to the internal _set_literal method.
246
+ """
247
+ return await self._set_literal(expected)
248
+
249
+ async def iter(self) -> typing.AsyncIterator[DF]:
250
+ if self._dataframe_type is None:
251
+ raise ValueError("No dataframe type set. Use open() to set the local dataframe type you want to use.")
252
+ return await flyte_dataset_transformer.iter_as(
253
+ self.literal, self._dataframe_type, updated_metadata=self.metadata
254
+ )
255
+
256
+
257
+ # flat the nested column map recursively
258
+ def flatten_dict(sub_dict: dict, parent_key: str = "") -> typing.Dict:
259
+ result = {}
260
+ for key, value in sub_dict.items():
261
+ current_key = f"{parent_key}.{key}" if parent_key else key
262
+ if isinstance(value, dict):
263
+ result.update(flatten_dict(sub_dict=value, parent_key=current_key))
264
+ elif is_dataclass(value):
265
+ fields = getattr(value, "__dataclass_fields__")
266
+ d = {k: v.type for k, v in fields.items()}
267
+ result.update(flatten_dict(sub_dict=d, parent_key=current_key))
268
+ elif hasattr(value, "model_fields"): # Pydantic model
269
+ d = {k: v.annotation for k, v in value.model_fields.items()}
270
+ result.update(flatten_dict(sub_dict=d, parent_key=current_key))
271
+ else:
272
+ result[current_key] = value
273
+ return result
274
+
275
+
276
+ def extract_cols_and_format(
277
+ t: typing.Any,
278
+ ) -> typing.Tuple[Type[T], Optional[typing.OrderedDict[str, Type]], Optional[str], Optional["pa.lib.Schema"]]:
279
+ """
280
+ Helper function, just used to iterate through Annotations and extract out the following information:
281
+ - base type, if not Annotated, it will just be the type that was passed in.
282
+ - column information, as a collections.OrderedDict,
283
+ - the storage format, as a ``DataFrameFormat`` (str),
284
+ - pa.lib.Schema
285
+
286
+ If more than one of any type of thing is found, an error will be raised.
287
+ If no instances of a given type are found, then None will be returned.
288
+
289
+ If we add more things, we should put all the returned items in a dataclass instead of just a tuple.
290
+
291
+ :param t: The incoming type which may or may not be Annotated
292
+ :return: Tuple representing
293
+ the original type,
294
+ optional OrderedDict of columns,
295
+ optional str for the format,
296
+ optional pyarrow Schema
297
+ """
298
+ fmt = ""
299
+ ordered_dict_cols = None
300
+ pa_schema = None
301
+ if get_origin(t) is Annotated:
302
+ base_type, *annotate_args = get_args(t)
303
+ for aa in annotate_args:
304
+ if hasattr(aa, "__annotations__"):
305
+ # handle dataclass argument
306
+ d = collections.OrderedDict()
307
+ d.update(aa.__annotations__)
308
+ ordered_dict_cols = d
309
+ elif isinstance(aa, dict):
310
+ d = collections.OrderedDict()
311
+ d.update(aa)
312
+ ordered_dict_cols = d
313
+ elif isinstance(aa, DataFrameFormat):
314
+ if fmt != "":
315
+ raise ValueError(f"A format was already specified {fmt}, cannot use {aa}")
316
+ fmt = aa
317
+ elif isinstance(aa, collections.OrderedDict):
318
+ if ordered_dict_cols is not None:
319
+ raise ValueError(f"Column information was already found {ordered_dict_cols}, cannot use {aa}")
320
+ ordered_dict_cols = aa
321
+ elif isinstance(aa, pa.lib.Schema):
322
+ if pa_schema is not None:
323
+ raise ValueError(f"Arrow schema was already found {pa_schema}, cannot use {aa}")
324
+ pa_schema = aa
325
+ return base_type, ordered_dict_cols, fmt, pa_schema
326
+
327
+ # We return None as the format instead of parquet or something because the transformer engine may find
328
+ # a better default for the given dataframe type.
329
+ return t, ordered_dict_cols, fmt, pa_schema
330
+
331
+
332
+ class DataFrameEncoder(ABC, Generic[T]):
333
+ def __init__(
334
+ self,
335
+ python_type: Type[T],
336
+ protocol: Optional[str] = None,
337
+ supported_format: Optional[str] = None,
338
+ ):
339
+ """
340
+ Extend this abstract class, implement the encode function, and register your concrete class with the
341
+ DataFrameTransformerEngine class in order for the core flytekit type engine to handle
342
+ dataframe libraries. This is the encoding interface, meaning it is used when there is a Python value that the
343
+ flytekit type engine is trying to convert into a Flyte Literal. For the other way, see
344
+ the DataFrameEncoder
345
+
346
+ :param python_type: The dataframe class in question that you want to register this encoder with
347
+ :param protocol: A prefix representing the storage driver (e.g. 's3, 'gs', 'bq', etc.). You can use either
348
+ "s3" or "s3://". They are the same since the "://" will just be stripped by the constructor.
349
+ If None, this encoder will be registered with all protocols that flytekit's data persistence layer
350
+ is capable of handling.
351
+ :param supported_format: Arbitrary string representing the format. If not supplied then an empty string
352
+ will be used. An empty string implies that the encoder works with any format. If the format being asked
353
+ for does not exist, the transformer engine will look for the "" encoder instead and write a warning.
354
+ """
355
+ self._python_type = python_type
356
+ self._protocol = protocol.replace("://", "") if protocol else None
357
+ self._supported_format = supported_format or ""
358
+
359
+ @property
360
+ def python_type(self) -> Type[T]:
361
+ return self._python_type
362
+
363
+ @property
364
+ def protocol(self) -> Optional[str]:
365
+ return self._protocol
366
+
367
+ @property
368
+ def supported_format(self) -> str:
369
+ return self._supported_format
370
+
371
+ @abstractmethod
372
+ async def encode(
373
+ self,
374
+ dataframe: DataFrame,
375
+ structured_dataset_type: types_pb2.StructuredDatasetType,
376
+ ) -> literals_pb2.StructuredDataset:
377
+ """
378
+ Even if the user code returns a plain dataframe instance, the dataset transformer engine will wrap the
379
+ incoming dataframe with defaults set for that dataframe
380
+ type. This simplifies this function's interface as a lot of data that could be specified by the user using
381
+ the
382
+ # TODO: Do we need to add a flag to indicate if it was wrapped by the transformer or by the user?
383
+
384
+ :param dataframe: This is a DataFrame wrapper object. See more info above.
385
+ :param structured_dataset_type: This the DataFrameType, as found in the LiteralType of the interface
386
+ of the task that invoked this encoding call. It is passed along to encoders so that authors of encoders
387
+ can include it in the returned literals.DataFrame. See the IDL for more information on why this
388
+ literal in particular carries the type information along with it. If the encoder doesn't supply it, it will
389
+ also be filled in after the encoder runs by the transformer engine.
390
+ :return: This function should return a DataFrame literal object. Do not confuse this with the
391
+ DataFrame wrapper class used as input to this function - that is the user facing Python class.
392
+ This function needs to return the IDL DataFrame.
393
+ """
394
+ raise NotImplementedError
395
+
396
+
397
+ class DataFrameDecoder(ABC, Generic[DF]):
398
+ def __init__(
399
+ self,
400
+ python_type: Type[DF],
401
+ protocol: Optional[str] = None,
402
+ supported_format: Optional[str] = None,
403
+ additional_protocols: Optional[List[str]] = None,
404
+ ):
405
+ """
406
+ Extend this abstract class, implement the decode function, and register your concrete class with the
407
+ DataFrameTransformerEngine class in order for the core flytekit type engine to handle
408
+ dataframe libraries. This is the decoder interface, meaning it is used when there is a Flyte Literal value,
409
+ and we have to get a Python value out of it. For the other way, see the DataFrameEncoder
410
+
411
+ :param python_type: The dataframe class in question that you want to register this decoder with
412
+ :param protocol: A prefix representing the storage driver (e.g. 's3, 'gs', 'bq', etc.). You can use either
413
+ "s3" or "s3://". They are the same since the "://" will just be stripped by the constructor.
414
+ If None, this decoder will be registered with all protocols that flytekit's data persistence layer
415
+ is capable of handling.
416
+ :param supported_format: Arbitrary string representing the format. If not supplied then an empty string
417
+ will be used. An empty string implies that the decoder works with any format. If the format being asked
418
+ for does not exist, the transformer enginer will look for the "" decoder instead and write a warning.
419
+ """
420
+ self._python_type = python_type
421
+ self._protocol = protocol.replace("://", "") if protocol else None
422
+ self._supported_format = supported_format or ""
423
+
424
+ @property
425
+ def python_type(self) -> Type[DF]:
426
+ return self._python_type
427
+
428
+ @property
429
+ def protocol(self) -> Optional[str]:
430
+ return self._protocol
431
+
432
+ @property
433
+ def supported_format(self) -> str:
434
+ return self._supported_format
435
+
436
+ @abstractmethod
437
+ async def decode(
438
+ self,
439
+ flyte_value: literals_pb2.StructuredDataset,
440
+ current_task_metadata: literals_pb2.StructuredDatasetMetadata,
441
+ ) -> Union[DF, typing.AsyncIterator[DF]]:
442
+ """
443
+ This is code that will be called by the dataset transformer engine to ultimately translate from a Flyte Literal
444
+ value into a Python instance.
445
+
446
+ :param flyte_value: This will be a Flyte IDL DataFrame Literal - do not confuse this with the
447
+ DataFrame class defined also in this module.
448
+ :param current_task_metadata: Metadata object containing the type (and columns if any) for the currently
449
+ executing task. This type may have more or less information than the type information bundled
450
+ inside the incoming flyte_value.
451
+ :return: This function can either return an instance of the dataframe that this decoder handles, or an iterator
452
+ of those dataframes.
453
+ """
454
+ raise NotImplementedError
455
+
456
+
457
+ def get_supported_types():
458
+ import numpy as _np
459
+
460
+ _SUPPORTED_TYPES: typing.Dict[Type, types_pb2.LiteralType] = { # type: ignore
461
+ _np.int32: types_pb2.LiteralType(simple=types_pb2.SimpleType.INTEGER),
462
+ _np.int64: types_pb2.LiteralType(simple=types_pb2.SimpleType.INTEGER),
463
+ _np.uint32: types_pb2.LiteralType(simple=types_pb2.SimpleType.INTEGER),
464
+ _np.uint64: types_pb2.LiteralType(simple=types_pb2.SimpleType.INTEGER),
465
+ int: types_pb2.LiteralType(simple=types_pb2.SimpleType.INTEGER),
466
+ _np.float32: types_pb2.LiteralType(simple=types_pb2.SimpleType.FLOAT),
467
+ _np.float64: types_pb2.LiteralType(simple=types_pb2.SimpleType.FLOAT),
468
+ float: types_pb2.LiteralType(simple=types_pb2.SimpleType.FLOAT),
469
+ _np.bool_: types_pb2.LiteralType(simple=types_pb2.SimpleType.BOOLEAN), # type: ignore
470
+ bool: types_pb2.LiteralType(simple=types_pb2.SimpleType.BOOLEAN),
471
+ _np.datetime64: types_pb2.LiteralType(simple=types_pb2.SimpleType.DATETIME),
472
+ _datetime.datetime: types_pb2.LiteralType(simple=types_pb2.SimpleType.DATETIME),
473
+ _np.timedelta64: types_pb2.LiteralType(simple=types_pb2.SimpleType.DURATION),
474
+ _datetime.timedelta: types_pb2.LiteralType(simple=types_pb2.SimpleType.DURATION),
475
+ _np.bytes_: types_pb2.LiteralType(simple=types_pb2.SimpleType.STRING),
476
+ _np.str_: types_pb2.LiteralType(simple=types_pb2.SimpleType.STRING),
477
+ _np.object_: types_pb2.LiteralType(simple=types_pb2.SimpleType.STRING),
478
+ str: types_pb2.LiteralType(simple=types_pb2.SimpleType.STRING),
479
+ }
480
+ return _SUPPORTED_TYPES
481
+
482
+
483
+ class DuplicateHandlerError(ValueError): ...
484
+
485
+
486
+ class DataFrameTransformerEngine(TypeTransformer[DataFrame]):
487
+ """
488
+ Think of this transformer as a higher-level meta transformer that is used for all the dataframe types.
489
+ If you are bringing a custom data frame type, or any data frame type, to flytekit, instead of
490
+ registering with the main type engine, you should register with this transformer instead.
491
+ """
492
+
493
+ ENCODERS: ClassVar[Dict[Type, Dict[str, Dict[str, DataFrameEncoder]]]] = {}
494
+ DECODERS: ClassVar[Dict[Type, Dict[str, Dict[str, DataFrameDecoder]]]] = {}
495
+ DEFAULT_PROTOCOLS: ClassVar[Dict[Type, str]] = {}
496
+ DEFAULT_FORMATS: ClassVar[Dict[Type, str]] = {}
497
+
498
+ Handlers = Union[DataFrameEncoder, DataFrameDecoder]
499
+ Renderers: ClassVar[Dict[Type, Renderable]] = {}
500
+
501
+ @classmethod
502
+ def _finder(cls, handler_map, df_type: Type, protocol: str, format: str):
503
+ # If there's an exact match, then we should use it.
504
+ try:
505
+ return handler_map[df_type][protocol][format]
506
+ except KeyError:
507
+ ...
508
+
509
+ fsspec_handler = None
510
+ protocol_specific_handler = None
511
+ single_handler = None
512
+ default_format = cls.DEFAULT_FORMATS.get(df_type, None)
513
+
514
+ try:
515
+ fss_handlers = handler_map[df_type]["fsspec"]
516
+ if format in fss_handlers:
517
+ fsspec_handler = fss_handlers[format]
518
+ elif GENERIC_FORMAT in fss_handlers:
519
+ fsspec_handler = fss_handlers[GENERIC_FORMAT]
520
+ else:
521
+ if default_format and default_format in fss_handlers and format == GENERIC_FORMAT:
522
+ fsspec_handler = fss_handlers[default_format]
523
+ else:
524
+ if len(fss_handlers) == 1 and format == GENERIC_FORMAT:
525
+ single_handler = next(iter(fss_handlers.values()))
526
+ else:
527
+ ...
528
+ except KeyError:
529
+ ...
530
+
531
+ try:
532
+ protocol_handlers = handler_map[df_type][protocol]
533
+ if GENERIC_FORMAT in protocol_handlers:
534
+ protocol_specific_handler = protocol_handlers[GENERIC_FORMAT]
535
+ else:
536
+ if default_format and default_format in protocol_handlers:
537
+ protocol_specific_handler = protocol_handlers[default_format]
538
+ else:
539
+ if len(protocol_handlers) == 1:
540
+ single_handler = next(iter(protocol_handlers.values()))
541
+ else:
542
+ ...
543
+
544
+ except KeyError:
545
+ ...
546
+
547
+ if protocol_specific_handler or fsspec_handler or single_handler:
548
+ return protocol_specific_handler or fsspec_handler or single_handler
549
+ else:
550
+ raise ValueError(f"Failed to find a handler for {df_type}, protocol [{protocol}], fmt ['{format}']")
551
+
552
+ @classmethod
553
+ def get_encoder(cls, df_type: Type, protocol: str, format: str):
554
+ return cls._finder(DataFrameTransformerEngine.ENCODERS, df_type, protocol, format)
555
+
556
+ @classmethod
557
+ def get_decoder(cls, df_type: Type, protocol: str, format: str) -> DataFrameDecoder:
558
+ return cls._finder(DataFrameTransformerEngine.DECODERS, df_type, protocol, format)
559
+
560
+ @classmethod
561
+ def _handler_finder(cls, h: Handlers, protocol: str) -> Dict[str, Handlers]:
562
+ if isinstance(h, DataFrameEncoder):
563
+ top_level = cls.ENCODERS
564
+ elif isinstance(h, DataFrameDecoder):
565
+ top_level = cls.DECODERS # type: ignore
566
+ else:
567
+ raise TypeError(f"We don't support this type of handler {h}")
568
+ if h.python_type not in top_level:
569
+ top_level[h.python_type] = {}
570
+ if protocol not in top_level[h.python_type]:
571
+ top_level[h.python_type][protocol] = {}
572
+ return top_level[h.python_type][protocol] # type: ignore
573
+
574
+ def __init__(self):
575
+ super().__init__("DataFrame Transformer", DataFrame)
576
+ self._type_assertions_enabled = False
577
+
578
+ @classmethod
579
+ def register_renderer(cls, python_type: Type, renderer: Renderable):
580
+ cls.Renderers[python_type] = renderer
581
+
582
+ @classmethod
583
+ def register(
584
+ cls,
585
+ h: Handlers,
586
+ default_for_type: bool = False,
587
+ override: bool = False,
588
+ default_format_for_type: bool = False,
589
+ default_storage_for_type: bool = False,
590
+ ):
591
+ """
592
+ Call this with any Encoder or Decoder to register it with the flytekit type system. If your handler does not
593
+ specify a protocol (e.g. s3, gs, etc.) field, then
594
+
595
+ :param h: The DataFrameEncoder or DataFrameDecoder you wish to register with this transformer.
596
+ :param default_for_type: If set, when a user returns from a task an instance of the dataframe the handler
597
+ handles, e.g. ``return pd.DataFrame(...)``, not wrapped around the ``StructuredDataset`` object, we will
598
+ use this handler's protocol and format as the default, effectively saying that this handler will be called.
599
+ Note that this shouldn't be set if your handler's protocol is None, because that implies that your handler
600
+ is capable of handling all the different storage protocols that flytekit's data persistence layer is aware of.
601
+ In these cases, the protocol is determined by the raw output data prefix set in the active context.
602
+ :param override: Override any previous registrations. If default_for_type is also set, this will also override
603
+ the default.
604
+ :param default_format_for_type: Unlike the default_for_type arg that will set this handler's format and storage
605
+ as the default, this will only set the format. Error if already set, unless override is specified.
606
+ :param default_storage_for_type: Same as above but only for the storage format. Error if already set,
607
+ unless override is specified.
608
+ """
609
+ if not (isinstance(h, DataFrameEncoder) or isinstance(h, DataFrameDecoder)):
610
+ raise TypeError(f"We don't support this type of handler {h}")
611
+
612
+ if h.protocol is None:
613
+ if default_for_type:
614
+ raise ValueError(f"Registering SD handler {h} with all protocols should never have default specified.")
615
+ try:
616
+ cls.register_for_protocol(
617
+ h, "fsspec", False, override, default_format_for_type, default_storage_for_type
618
+ )
619
+ except DuplicateHandlerError:
620
+ ...
621
+
622
+ elif h.protocol == "":
623
+ raise ValueError(f"Use None instead of empty string for registering handler {h}")
624
+ else:
625
+ cls.register_for_protocol(
626
+ h, h.protocol, default_for_type, override, default_format_for_type, default_storage_for_type
627
+ )
628
+
629
+ @classmethod
630
+ def register_for_protocol(
631
+ cls,
632
+ h: Handlers,
633
+ protocol: str,
634
+ default_for_type: bool,
635
+ override: bool,
636
+ default_format_for_type: bool,
637
+ default_storage_for_type: bool,
638
+ ):
639
+ """
640
+ See the main register function instead.
641
+ """
642
+ if protocol == "/":
643
+ protocol = "file"
644
+ lowest_level = cls._handler_finder(h, protocol)
645
+ if h.supported_format in lowest_level and override is False:
646
+ raise DuplicateHandlerError(
647
+ f"Already registered a handler for {(h.python_type, protocol, h.supported_format)}"
648
+ )
649
+ lowest_level[h.supported_format] = h
650
+ logger.debug(
651
+ f"Registered {h.__class__.__name__} as handler for {h.python_type.__class__.__name__},"
652
+ f" protocol {protocol}, fmt {h.supported_format}"
653
+ )
654
+
655
+ if (default_format_for_type or default_for_type) and h.supported_format != GENERIC_FORMAT:
656
+ if h.python_type in cls.DEFAULT_FORMATS and not override:
657
+ if cls.DEFAULT_FORMATS[h.python_type] != h.supported_format:
658
+ logger.info(
659
+ f"Not using handler {h.__class__.__name__} with format {h.supported_format}"
660
+ f" as default for {h.python_type.__class__.__name__},"
661
+ f" {cls.DEFAULT_FORMATS[h.python_type]} already specified."
662
+ )
663
+ else:
664
+ logger.debug(f"Use {type(h).__name__} as default handler for {h.python_type.__class__.__name__}.")
665
+ cls.DEFAULT_FORMATS[h.python_type] = h.supported_format
666
+ if default_storage_for_type or default_for_type:
667
+ if h.protocol in cls.DEFAULT_PROTOCOLS and not override:
668
+ logger.debug(
669
+ f"Not using handler {h} with storage protocol {h.protocol}"
670
+ f" as default for {h.python_type}, {cls.DEFAULT_PROTOCOLS[h.python_type]} already specified."
671
+ )
672
+ else:
673
+ logger.debug(f"Using storage {protocol} for dataframes of type {h.python_type} from handler {h}")
674
+ cls.DEFAULT_PROTOCOLS[h.python_type] = protocol
675
+
676
+ # Register with the type engine as well
677
+ # The semantics as of now are such that it doesn't matter which order these transformers are loaded in, as
678
+ # long as the older Pandas/FlyteSchema transformer do not also specify the override
679
+ engine = DataFrameTransformerEngine()
680
+ TypeEngine.register_additional_type(engine, h.python_type, override=True)
681
+
682
+ def assert_type(self, t: Type[DataFrame], v: typing.Any):
683
+ return
684
+
685
+ async def to_literal(
686
+ self,
687
+ python_val: Union[DataFrame, typing.Any],
688
+ python_type: Union[Type[DataFrame], Type],
689
+ expected: types_pb2.LiteralType,
690
+ ) -> literals_pb2.Literal:
691
+ # Make a copy in case we need to hand off to encoders, since we can't be sure of mutations.
692
+ python_type, *_attrs = extract_cols_and_format(python_type)
693
+ sdt = types_pb2.StructuredDatasetType(format=self.DEFAULT_FORMATS.get(python_type, GENERIC_FORMAT))
694
+
695
+ if issubclass(python_type, DataFrame) and not isinstance(python_val, DataFrame):
696
+ # Catch a common mistake
697
+ raise TypeTransformerFailedError(
698
+ f"Expected a DataFrame instance, but got {type(python_val)} instead."
699
+ f" Did you forget to wrap your dataframe in a DataFrame instance?"
700
+ )
701
+
702
+ if expected and expected.structured_dataset_type:
703
+ sdt = types_pb2.StructuredDatasetType(
704
+ columns=expected.structured_dataset_type.columns,
705
+ format=expected.structured_dataset_type.format,
706
+ external_schema_type=expected.structured_dataset_type.external_schema_type,
707
+ external_schema_bytes=expected.structured_dataset_type.external_schema_bytes,
708
+ )
709
+
710
+ # If the type signature has the DataFrame class, it will, or at least should, also be a
711
+ # DataFrame instance.
712
+ if isinstance(python_val, DataFrame):
713
+ # There are three cases that we need to take care of here.
714
+
715
+ # 1. A task returns a DataFrame that was just a passthrough input. If this happens
716
+ # then return the original literals.DataFrame without invoking any encoder
717
+ #
718
+ # Ex.
719
+ # def t1(dataset: Annotated[DataFrame, my_cols]) -> Annotated[DataFrame, my_cols]:
720
+ # return dataset
721
+ if python_val._literal_sd is not None:
722
+ if python_val._already_uploaded:
723
+ return literals_pb2.Literal(scalar=literals_pb2.Scalar(structured_dataset=python_val._literal_sd))
724
+ if python_val.val is not None:
725
+ raise ValueError(
726
+ f"Shouldn't have specified both literal {python_val._literal_sd} and dataframe {python_val.val}"
727
+ )
728
+ return literals_pb2.Literal(scalar=literals_pb2.Scalar(structured_dataset=python_val._literal_sd))
729
+
730
+ # 2. A task returns a python DataFrame with an uri.
731
+ # Note: this case is also what happens we start a local execution of a task with a python DataFrame.
732
+ # It gets converted into a literal first, then back into a python DataFrame.
733
+ #
734
+ # Ex.
735
+ # def t2(uri: str) -> Annotated[DataFrame, my_cols]
736
+ # return DataFrame(uri=uri)
737
+ if python_val.val is None:
738
+ uri = python_val.uri
739
+ format_val = python_val.format
740
+
741
+ # Check the user-specified uri
742
+ if not uri:
743
+ raise ValueError(f"If dataframe is not specified, then the uri should be specified. {python_val}")
744
+ if not storage.is_remote(uri):
745
+ uri = await storage.put(uri, recursive=True)
746
+
747
+ # Check the user-specified format
748
+ # When users specify format for a DataFrame, the format should be retained
749
+ # conditionally. For details, please refer to https://github.com/flyteorg/flyte/issues/6096.
750
+ # Following illustrates why we can't always copy the user-specified file_format over:
751
+ #
752
+ # @task
753
+ # def modify_format(df: Annotated[DataFrame, {}, "task-format"]) -> DataFrame:
754
+ # return df
755
+ #
756
+ # df = DataFrame(uri="s3://my-s3-bucket/df.parquet", format="user-format")
757
+ # df2 = modify_format(df=df)
758
+ #
759
+ # In this case, we expect the df2.format to be task-format (as shown in Annotated),
760
+ # not user-format. If we directly copy the user-specified format over,
761
+ # the type hint information will be missing.
762
+ if sdt.format == GENERIC_FORMAT and format_val != GENERIC_FORMAT:
763
+ sdt.format = format_val
764
+
765
+ sd_model = literals_pb2.StructuredDataset(
766
+ uri=uri,
767
+ metadata=literals_pb2.StructuredDatasetMetadata(structured_dataset_type=sdt),
768
+ )
769
+ return literals_pb2.Literal(scalar=literals_pb2.Scalar(structured_dataset=sd_model))
770
+
771
+ # 3. This is the third and probably most common case. The python DataFrame object wraps a dataframe
772
+ # that we will need to invoke an encoder for. Figure out which encoder to call and invoke it.
773
+ df_type = type(python_val.val)
774
+ protocol = self._protocol_from_type_or_prefix(df_type, python_val.uri)
775
+
776
+ return await self.encode(
777
+ python_val,
778
+ df_type,
779
+ protocol,
780
+ sdt.format,
781
+ sdt,
782
+ )
783
+
784
+ # Otherwise assume it's a dataframe instance. Wrap it with some defaults
785
+ fmt = self.DEFAULT_FORMATS.get(python_type, "")
786
+ protocol = self._protocol_from_type_or_prefix(python_type)
787
+ meta = literals_pb2.StructuredDatasetMetadata(
788
+ structured_dataset_type=expected.structured_dataset_type if expected else None
789
+ )
790
+
791
+ fdf = DataFrame.from_df(val=python_val)
792
+ fdf._metadata = meta
793
+ return await self.encode(fdf, python_type, protocol, fmt, sdt)
794
+
795
+ def _protocol_from_type_or_prefix(self, df_type: Type, uri: Optional[str] = None) -> str:
796
+ """
797
+ Get the protocol from the default, if missing, then look it up from the uri if provided, if not then look
798
+ up from the provided context's file access.
799
+ """
800
+ if df_type in self.DEFAULT_PROTOCOLS:
801
+ return self.DEFAULT_PROTOCOLS[df_type]
802
+ else:
803
+ from flyte._context import internal_ctx
804
+
805
+ ctx = internal_ctx()
806
+ protocol = get_protocol(uri or ctx.raw_data.path)
807
+ logger.debug(
808
+ f"No default protocol for type {df_type} found, using {protocol} from output prefix {ctx.raw_data.path}"
809
+ )
810
+ return protocol
811
+
812
+ async def encode(
813
+ self,
814
+ df: DataFrame,
815
+ df_type: Type,
816
+ protocol: str,
817
+ format: str,
818
+ structured_literal_type: types_pb2.StructuredDatasetType,
819
+ ) -> literals_pb2.Literal:
820
+ handler: DataFrameEncoder
821
+ handler = self.get_encoder(df_type, protocol, format)
822
+
823
+ sd_model = await handler.encode(df, structured_literal_type)
824
+ # This block is here in case the encoder did not set the type information in the metadata. Since this literal
825
+ # is special in that it carries around the type itself, we want to make sure the type info therein is at
826
+ # least as good as the type of the interface.
827
+
828
+ if sd_model.metadata is None:
829
+ sd_model.metadata = literals_pb2.StructuredDatasetMetadata(structured_dataset_type=structured_literal_type)
830
+ if sd_model.metadata and sd_model.metadata.structured_dataset_type is None:
831
+ sd_model.metadata.structured_dataset_type = structured_literal_type
832
+ # Always set the format here to the format of the handler.
833
+ # Note that this will always be the same as the incoming format except for when the fallback handler
834
+ # with a format of "" is used.
835
+ sd_model.metadata.structured_dataset_type.format = handler.supported_format
836
+ lit = literals_pb2.Literal(scalar=literals_pb2.Scalar(structured_dataset=sd_model))
837
+
838
+ # Because the handler.encode may have uploaded something, and because the sd may end up living inside a
839
+ # dataclass, we need to modify any uploaded flyte:// urls here. Needed here even though the Type engine
840
+ # already does this because the DataframeTransformerEngine may be called directly.
841
+ modify_literal_uris(lit)
842
+ df._literal_sd = sd_model
843
+ df._already_uploaded = True
844
+ return lit
845
+
846
+ async def to_python_value(
847
+ self, lv: literals_pb2.Literal, expected_python_type: Type[T] | DataFrame
848
+ ) -> T | DataFrame:
849
+ """
850
+ The only tricky thing with converting a Literal (say the output of an earlier task), to a Python value at
851
+ the start of a task execution, is the column subsetting behavior. For example, if you have,
852
+
853
+ def t1() -> Annotated[StructuredDataset, kwtypes(col_a=int, col_b=float)]: ...
854
+ def t2(in_a: Annotated[StructuredDataset, kwtypes(col_b=float)]): ...
855
+
856
+ where t2(in_a=t1()), when t2 does in_a.open(pd.DataFrame).all(), it should get a DataFrame
857
+ with only one column.
858
+
859
+ +-----------------------------+-----------------------------------------+--------------------------------------+
860
+ | | StructuredDatasetType of the incoming Literal |
861
+ +-----------------------------+-----------------------------------------+--------------------------------------+
862
+ | StructuredDatasetType | Has columns defined | [] columns or None |
863
+ | of currently running task | | |
864
+ +=============================+=========================================+======================================+
865
+ | Has columns | The StructuredDatasetType passed to the decoder will have the columns |
866
+ | defined | as defined by the type annotation of the currently running task. |
867
+ | | |
868
+ | | Decoders **should** then subset the incoming data to the columns requested. |
869
+ | | |
870
+ +-----------------------------+-----------------------------------------+--------------------------------------+
871
+ | [] columns or None | StructuredDatasetType passed to decoder | StructuredDatasetType passed to the |
872
+ | | will have the columns from the incoming | decoder will have an empty list of |
873
+ | | Literal. This is the scenario where | columns. |
874
+ | | the Literal returned by the running | |
875
+ | | task will have more information than | |
876
+ | | the running task's signature. | |
877
+ +-----------------------------+-----------------------------------------+--------------------------------------+
878
+ """
879
+ if lv.HasField("scalar") and lv.scalar.HasField("binary"):
880
+ raise TypeTransformerFailedError("Attribute access unsupported.")
881
+
882
+ # Detect annotations and extract out all the relevant information that the user might supply
883
+ expected_python_type, column_dict, _storage_fmt, _pa_schema = extract_cols_and_format(expected_python_type)
884
+
885
+ # Start handling for DataFrame scalars, first look at the columns
886
+ incoming_columns = lv.scalar.structured_dataset.metadata.structured_dataset_type.columns
887
+
888
+ # If the incoming literal, also doesn't have columns, then we just have an empty list, so initialize here
889
+ final_dataset_columns = []
890
+ # If the current running task's input does not have columns defined, or has an empty list of columns
891
+ if column_dict is None or len(column_dict) == 0:
892
+ # but if it does, then we just copy it over
893
+ if incoming_columns is not None and incoming_columns != []:
894
+ final_dataset_columns = incoming_columns[:]
895
+ # If the current running task's input does have columns defined
896
+ else:
897
+ final_dataset_columns = self._convert_ordered_dict_of_columns_to_list(column_dict)
898
+
899
+ new_sdt = types_pb2.StructuredDatasetType(
900
+ columns=final_dataset_columns,
901
+ format=lv.scalar.structured_dataset.metadata.structured_dataset_type.format,
902
+ external_schema_type=lv.scalar.structured_dataset.metadata.structured_dataset_type.external_schema_type,
903
+ external_schema_bytes=lv.scalar.structured_dataset.metadata.structured_dataset_type.external_schema_bytes,
904
+ )
905
+ metad = literals_pb2.StructuredDatasetMetadata(structured_dataset_type=new_sdt)
906
+
907
+ # A DataFrame type, for example
908
+ # t1(input_a: DataFrame) # or
909
+ # t1(input_a: Annotated[DataFrame, my_cols])
910
+ if issubclass(expected_python_type, DataFrame):
911
+ fdf = DataFrame(format=metad.structured_dataset_type.format, uri=lv.scalar.structured_dataset.uri)
912
+ fdf._already_uploaded = True
913
+ fdf._literal_sd = lv.scalar.structured_dataset
914
+ fdf._metadata = metad
915
+ return fdf
916
+
917
+ # If the requested type was not a flyte.DataFrame, then it means it was a raw dataframe type, which means
918
+ # we should do the opening/downloading and whatever else it might entail right now. No iteration option here.
919
+ return await self.open_as(lv.scalar.structured_dataset, df_type=expected_python_type, updated_metadata=metad)
920
+
921
+ def to_html(self, python_val: typing.Any, expected_python_type: Type[T]) -> str:
922
+ if isinstance(python_val, DataFrame):
923
+ if python_val.val is not None:
924
+ df = python_val.val
925
+ else:
926
+ # Here we only render column information by default instead of opening the structured dataset.
927
+ col = typing.cast(DataFrame, python_val).columns()
928
+ dataframe = pd.DataFrame(col, ["column type"])
929
+ return dataframe.to_html() # type: ignore
930
+ else:
931
+ df = python_val
932
+
933
+ if type(df) in self.Renderers:
934
+ return self.Renderers[type(df)].to_html(df)
935
+ else:
936
+ raise NotImplementedError(f"Could not find a renderer for {type(df)} in {self.Renderers}")
937
+
938
+ async def open_as(
939
+ self,
940
+ sd: literals_pb2.StructuredDataset,
941
+ df_type: Type[DF],
942
+ updated_metadata: literals_pb2.StructuredDatasetMetadata,
943
+ ) -> DF:
944
+ """
945
+ :param sd:
946
+ :param df_type:
947
+ :param updated_metadata: New metadata type, since it might be different from the metadata in the literal.
948
+ :return: dataframe. It could be pandas dataframe or arrow table, etc.
949
+ """
950
+ protocol = get_protocol(sd.uri)
951
+ decoder = self.get_decoder(df_type, protocol, sd.metadata.structured_dataset_type.format)
952
+ result = await decoder.decode(sd, updated_metadata)
953
+ return typing.cast(DF, result)
954
+
955
+ async def iter_as(
956
+ self,
957
+ sd: literals_pb2.StructuredDataset,
958
+ df_type: Type[DF],
959
+ updated_metadata: literals_pb2.StructuredDatasetMetadata,
960
+ ) -> typing.AsyncIterator[DF]:
961
+ protocol = get_protocol(sd.uri)
962
+ decoder = self.DECODERS[df_type][protocol][sd.metadata.structured_dataset_type.format]
963
+ result: Union[Coroutine[Any, Any, DF], Coroutine[Any, Any, typing.AsyncIterator[DF]]] = decoder.decode(
964
+ sd, updated_metadata
965
+ )
966
+ if not isinstance(result, types.AsyncGeneratorType):
967
+ raise ValueError(f"Decoder {decoder} didn't return an async iterator {result} but should have from {sd}")
968
+ return result
969
+
970
+ def _get_dataset_column_literal_type(self, t: Type) -> types_pb2.LiteralType:
971
+ if t in get_supported_types():
972
+ return get_supported_types()[t]
973
+ origin = getattr(t, "__origin__", None)
974
+ if origin is list:
975
+ return types_pb2.LiteralType(collection_type=self._get_dataset_column_literal_type(t.__args__[0]))
976
+ if origin is dict:
977
+ return types_pb2.LiteralType(map_value_type=self._get_dataset_column_literal_type(t.__args__[1]))
978
+ raise AssertionError(f"type {t} is currently not supported by DataFrame")
979
+
980
+ def _convert_ordered_dict_of_columns_to_list(
981
+ self, column_map: typing.Optional[typing.OrderedDict[str, Type]]
982
+ ) -> typing.List[types_pb2.StructuredDatasetType.DatasetColumn]:
983
+ converted_cols: typing.List[types_pb2.StructuredDatasetType.DatasetColumn] = []
984
+ if column_map is None or len(column_map) == 0:
985
+ return converted_cols
986
+ flat_column_map = flatten_dict(column_map)
987
+ for k, v in flat_column_map.items():
988
+ lt = self._get_dataset_column_literal_type(v)
989
+ converted_cols.append(types_pb2.StructuredDatasetType.DatasetColumn(name=k, literal_type=lt))
990
+ return converted_cols
991
+
992
+ def _get_dataset_type(self, t: typing.Union[Type[DataFrame], typing.Any]) -> types_pb2.StructuredDatasetType:
993
+ _original_python_type, column_map, storage_format, pa_schema = extract_cols_and_format(t) # type: ignore
994
+
995
+ # Get the column information
996
+ converted_cols: typing.List[types_pb2.StructuredDatasetType.DatasetColumn] = (
997
+ self._convert_ordered_dict_of_columns_to_list(column_map)
998
+ )
999
+
1000
+ return types_pb2.StructuredDatasetType(
1001
+ columns=converted_cols,
1002
+ format=storage_format,
1003
+ external_schema_type="arrow" if pa_schema else None,
1004
+ external_schema_bytes=typing.cast(pa.lib.Schema, pa_schema).to_string().encode() if pa_schema else None,
1005
+ )
1006
+
1007
+ def get_literal_type(self, t: typing.Union[Type[DataFrame], typing.Any]) -> types_pb2.LiteralType:
1008
+ """
1009
+ Provide a concrete implementation so that writers of custom dataframe handlers since there's nothing that
1010
+ special about the literal type. Any dataframe type will always be associated with the structured dataset type.
1011
+ The other aspects of it - columns, external schema type, etc. can be read from associated metadata.
1012
+
1013
+ :param t: The python dataframe type, which is mostly ignored.
1014
+ """
1015
+ return types_pb2.LiteralType(structured_dataset_type=self._get_dataset_type(t))
1016
+
1017
+ def guess_python_type(self, literal_type: types_pb2.LiteralType) -> Type[DataFrame]:
1018
+ # todo: technically we should return the dataframe type specified in the constructor, but to do that,
1019
+ # we'd have to store that, which we don't do today. See possibly #1363
1020
+ if literal_type.HasField("structured_dataset_type"):
1021
+ return DataFrame
1022
+ raise ValueError(f"DataFrameTransformerEngine cannot reverse {literal_type}")
1023
+
1024
+
1025
+ flyte_dataset_transformer = DataFrameTransformerEngine()
1026
+ TypeEngine.register(flyte_dataset_transformer)