forked from logicalclocks/hopsworks-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython.py
1626 lines (1487 loc) · 63.2 KB
/
python.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright 2020 Logical Clocks AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
import json
import logging
import math
import numbers
import os
import random
import re
import sys
import uuid
import warnings
from datetime import datetime, timedelta, timezone
from io import BytesIO
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Literal,
Optional,
Tuple,
Union,
)
from hsfs.core.type_systems import (
cast_column_to_offline_type,
cast_column_to_online_type,
)
if TYPE_CHECKING:
import great_expectations
import boto3
import hsfs
import pandas as pd
import pyarrow as pa
from botocore.response import StreamingBody
from hopsworks_common import client
from hopsworks_common.client.exceptions import FeatureStoreException
from hopsworks_common.core.constants import HAS_POLARS, polars_not_installed_message
from hopsworks_common.decorators import uses_great_expectations, uses_polars
from hsfs import (
feature,
feature_view,
transformation_function,
util,
)
from hsfs import storage_connector as sc
from hsfs.constructor import query
from hsfs.core import (
dataset_api,
feature_group_api,
feature_view_api,
ingestion_job_conf,
job,
job_api,
kafka_engine,
statistics_api,
storage_connector_api,
training_dataset_api,
training_dataset_job_conf,
transformation_function_engine,
)
from hsfs.core.constants import (
HAS_AIOMYSQL,
HAS_GREAT_EXPECTATIONS,
HAS_NUMPY,
HAS_PANDAS,
HAS_PYARROW,
HAS_SQLALCHEMY,
)
from hsfs.core.type_systems import PYARROW_HOPSWORKS_DTYPE_MAPPING
from hsfs.core.vector_db_client import VectorDbClient
from hsfs.feature_group import ExternalFeatureGroup, FeatureGroup
from hsfs.training_dataset import TrainingDataset
from hsfs.training_dataset_feature import TrainingDatasetFeature
from hsfs.training_dataset_split import TrainingDatasetSplit
if HAS_GREAT_EXPECTATIONS:
import great_expectations
if HAS_NUMPY:
import numpy as np
if HAS_AIOMYSQL and HAS_SQLALCHEMY:
from hsfs.core import util_sql
if HAS_SQLALCHEMY:
from sqlalchemy import sql
if HAS_PANDAS:
from hsfs.core.type_systems import convert_pandas_dtype_to_offline_type
if HAS_POLARS:
import polars as pl
_logger = logging.getLogger(__name__)
class Engine:
def __init__(self) -> None:
_logger.debug("Initialising Python Engine...")
self._dataset_api: dataset_api.DatasetApi = dataset_api.DatasetApi()
self._job_api: job_api.JobApi = job_api.JobApi()
self._feature_group_api: feature_group_api.FeatureGroupApi = (
feature_group_api.FeatureGroupApi()
)
self._storage_connector_api: storage_connector_api.StorageConnectorApi = (
storage_connector_api.StorageConnectorApi()
)
# cache the sql engine which contains the connection pool
self._mysql_online_fs_engine = None
_logger.info("Python Engine initialized.")
def sql(
self,
sql_query: str,
feature_store: str,
online_conn: Optional[sc.JdbcConnector],
dataframe_type: str,
read_options: Optional[Dict[str, Any]],
schema: Optional[List[feature.Feature]] = None,
) -> Union[pd.DataFrame, pl.DataFrame]:
if not online_conn:
return self._sql_offline(
sql_query,
dataframe_type,
schema,
arrow_flight_config=read_options.get("arrow_flight_config", {})
if read_options
else {},
)
else:
return self._jdbc(
sql_query, online_conn, dataframe_type, read_options, schema
)
def is_flyingduck_query_supported(
self, query: "query.Query", read_options: Optional[Dict[str, Any]] = None
) -> bool:
from hsfs.core import arrow_flight_client
return arrow_flight_client.is_query_supported(query, read_options or {})
def _validate_dataframe_type(self, dataframe_type: str):
if not isinstance(dataframe_type, str) or dataframe_type.lower() not in [
"pandas",
"polars",
"numpy",
"python",
"default",
]:
raise FeatureStoreException(
f'dataframe_type : {dataframe_type} not supported. Possible values are "default", "pandas", "polars", "numpy" or "python"'
)
def _sql_offline(
self,
sql_query: str,
dataframe_type: str,
schema: Optional[List["feature.Feature"]] = None,
arrow_flight_config: Optional[Dict[str, Any]] = None,
) -> Union[pd.DataFrame, pl.DataFrame]:
self._validate_dataframe_type(dataframe_type)
if isinstance(sql_query, dict) and "query_string" in sql_query:
from hsfs.core import arrow_flight_client
result_df = util.run_with_loading_animation(
"Reading data from Hopsworks, using Hopsworks Feature Query Service",
arrow_flight_client.get_instance().read_query,
sql_query,
arrow_flight_config or {},
dataframe_type,
)
else:
raise ValueError(
"Reading data with Hive is not supported when using hopsworks client version >= 4.0"
)
if schema:
result_df = Engine.cast_columns(result_df, schema)
return self._return_dataframe_type(result_df, dataframe_type)
def _jdbc(
self,
sql_query: str,
connector: sc.JdbcConnector,
dataframe_type: str,
read_options: Optional[Dict[str, Any]],
schema: Optional[List[feature.Feature]] = None,
) -> Union[pd.DataFrame, pl.DataFrame]:
self._validate_dataframe_type(dataframe_type)
if self._mysql_online_fs_engine is None:
self._mysql_online_fs_engine = util_sql.create_mysql_engine(
connector,
(
client._is_external()
if "external" not in read_options
else read_options["external"]
),
)
with self._mysql_online_fs_engine.connect() as mysql_conn:
if "sqlalchemy" in str(type(mysql_conn)):
sql_query = sql.text(sql_query)
if dataframe_type.lower() == "polars":
if not HAS_POLARS:
raise ModuleNotFoundError(polars_not_installed_message)
result_df = pl.read_database(sql_query, mysql_conn)
else:
result_df = pd.read_sql(sql_query, mysql_conn)
if schema:
result_df = Engine.cast_columns(result_df, schema, online=True)
return self._return_dataframe_type(result_df, dataframe_type)
def read(
self,
storage_connector: sc.StorageConnector,
data_format: str,
read_options: Optional[Dict[str, Any]],
location: Optional[str],
dataframe_type: Literal["polars", "pandas", "default"],
) -> Union[pd.DataFrame, pl.DataFrame]:
if not data_format:
raise FeatureStoreException("data_format is not specified")
if storage_connector.type == storage_connector.HOPSFS:
df_list = self._read_hopsfs(
location, data_format, read_options, dataframe_type
)
elif storage_connector.type == storage_connector.S3:
df_list = self._read_s3(
storage_connector, location, data_format, dataframe_type
)
else:
raise NotImplementedError(
"{} Storage Connectors for training datasets are not supported yet for external environments.".format(
storage_connector.type
)
)
if dataframe_type.lower() == "polars":
if not HAS_POLARS:
raise ModuleNotFoundError(polars_not_installed_message)
# Below check performed since some files materialized when creating training data are empty
# If empty dataframe is in df_list then polars cannot concatenate df_list due to schema mismatch
# However if the entire split contains only empty files which can occur when the data size is very small then one of the empty dataframe is return so that the column names can be accessed.
non_empty_df_list = [df for df in df_list if not df.is_empty()]
if non_empty_df_list:
return self._return_dataframe_type(
pl.concat(non_empty_df_list), dataframe_type=dataframe_type
)
else:
return df_list[0]
else:
return self._return_dataframe_type(
pd.concat(df_list, ignore_index=True), dataframe_type=dataframe_type
)
def _read_pandas(self, data_format: str, obj: Any) -> pd.DataFrame:
if data_format.lower() == "csv":
return pd.read_csv(obj)
elif data_format.lower() == "tsv":
return pd.read_csv(obj, sep="\t")
elif data_format.lower() == "parquet" and isinstance(obj, StreamingBody):
return pd.read_parquet(BytesIO(obj.read()))
elif data_format.lower() == "parquet":
return pd.read_parquet(obj)
else:
raise TypeError(
"{} training dataset format is not supported to read as pandas dataframe.".format(
data_format
)
)
@uses_polars
def _read_polars(
self, data_format: Literal["csv", "tsv", "parquet"], obj: Any
) -> pl.DataFrame:
if not HAS_POLARS:
raise ModuleNotFoundError(polars_not_installed_message)
if data_format.lower() == "csv":
return pl.read_csv(obj)
elif data_format.lower() == "tsv":
return pl.read_csv(obj, separator="\t")
elif data_format.lower() == "parquet" and isinstance(obj, StreamingBody):
return pl.read_parquet(BytesIO(obj.read()), use_pyarrow=True)
elif data_format.lower() == "parquet":
return pl.read_parquet(obj, use_pyarrow=True)
else:
raise TypeError(
"{} training dataset format is not supported to read as polars dataframe.".format(
data_format
)
)
def _is_metadata_file(self, path):
return Path(path).stem.startswith("_")
def _read_hopsfs(
self,
location: str,
data_format: str,
read_options: Optional[Dict[str, Any]] = None,
dataframe_type: str = "default",
) -> List[Union[pd.DataFrame, pl.DataFrame]]:
return self._read_hopsfs_remote(
location, data_format, read_options or {}, dataframe_type
)
# This read method uses the Hopsworks REST APIs or Flyingduck Server
# To read the training dataset content, this to allow users to read Hopsworks training dataset from outside
def _read_hopsfs_remote(
self,
location: str,
data_format: str,
read_options: Optional[Dict[str, Any]] = None,
dataframe_type: str = "default",
) -> List[Union[pd.DataFrame, pl.DataFrame]]:
total_count = 10000
offset = 0
df_list = []
if read_options is None:
read_options = {}
while offset < total_count:
total_count, inode_list = self._dataset_api.list_files(
location, offset, 100
)
for inode in inode_list:
if not self._is_metadata_file(inode.path):
from hsfs.core import arrow_flight_client
if arrow_flight_client.is_data_format_supported(
data_format, read_options
):
arrow_flight_config = read_options.get("arrow_flight_config")
df = arrow_flight_client.get_instance().read_path(
inode.path,
arrow_flight_config,
dataframe_type=dataframe_type,
)
else:
content_stream = self._dataset_api.read_content(inode.path)
if dataframe_type.lower() == "polars":
df = self._read_polars(
data_format, BytesIO(content_stream.content)
)
else:
df = self._read_pandas(
data_format, BytesIO(content_stream.content)
)
df_list.append(df)
offset += 1
return df_list
def _read_s3(
self,
storage_connector: sc.S3Connector,
location: str,
data_format: str,
dataframe_type: str = "default",
) -> List[Union[pd.DataFrame, pl.DataFrame]]:
# get key prefix
path_parts = location.replace("s3://", "").split("/")
_ = path_parts.pop(0) # pop first element -> bucket
prefix = "/".join(path_parts)
if storage_connector.session_token is not None:
s3 = boto3.client(
"s3",
aws_access_key_id=storage_connector.access_key,
aws_secret_access_key=storage_connector.secret_key,
aws_session_token=storage_connector.session_token,
)
else:
s3 = boto3.client(
"s3",
aws_access_key_id=storage_connector.access_key,
aws_secret_access_key=storage_connector.secret_key,
)
df_list = []
object_list = {"is_truncated": True}
while object_list.get("is_truncated", False):
if "NextContinuationToken" in object_list:
object_list = s3.list_objects_v2(
Bucket=storage_connector.bucket,
Prefix=prefix,
MaxKeys=1000,
ContinuationToken=object_list["NextContinuationToken"],
)
else:
object_list = s3.list_objects_v2(
Bucket=storage_connector.bucket,
Prefix=prefix,
MaxKeys=1000,
)
for obj in object_list["Contents"]:
if not self._is_metadata_file(obj["Key"]) and obj["Size"] > 0:
obj = s3.get_object(
Bucket=storage_connector.bucket,
Key=obj["Key"],
)
if dataframe_type.lower() == "polars":
df_list.append(self._read_polars(data_format, obj["Body"]))
else:
df_list.append(self._read_pandas(data_format, obj["Body"]))
return df_list
def read_options(
self, data_format: Optional[str], provided_options: Optional[Dict[str, Any]]
) -> Dict[str, Any]:
return provided_options or {}
def read_stream(
self,
storage_connector: sc.StorageConnector,
message_format: Any,
schema: Any,
options: Optional[Dict[str, Any]],
include_metadata: bool,
) -> Any:
raise NotImplementedError(
"Streaming Sources are not supported for pure Python Environments."
)
def show(
self,
sql_query: str,
feature_store: str,
n: int,
online_conn: sc.JdbcConnector,
read_options: Optional[Dict[str, Any]] = None,
) -> Union[pd.DataFrame, pl.DataFrame]:
return self.sql(
sql_query, feature_store, online_conn, "default", read_options or {}
).head(n)
def read_vector_db(
self,
feature_group: "hsfs.feature_group.FeatureGroup",
n: int = None,
dataframe_type: str = "default",
) -> Union[pd.DataFrame, pl.DataFrame, np.ndarray, List[List[Any]]]:
dataframe_type = dataframe_type.lower()
self._validate_dataframe_type(dataframe_type)
results = VectorDbClient.read_feature_group(feature_group, n)
feature_names = [f.name for f in feature_group.features]
if dataframe_type == "polars":
if not HAS_POLARS:
raise ModuleNotFoundError(polars_not_installed_message)
df = pl.DataFrame(results, schema=feature_names)
else:
df = pd.DataFrame(results, columns=feature_names, index=None)
return self._return_dataframe_type(df, dataframe_type)
def register_external_temporary_table(
self, external_fg: ExternalFeatureGroup, alias: str
) -> None:
# No op to avoid query failure
pass
def register_delta_temporary_table(
self, delta_fg_alias, feature_store_id, feature_store_name, read_options
):
# No op to avoid query failure
pass
def register_hudi_temporary_table(
self,
hudi_fg_alias: "hsfs.constructor.hudi_feature_group_alias.HudiFeatureGroupAlias",
feature_store_id: int,
feature_store_name: str,
read_options: Optional[Dict[str, Any]],
) -> None:
if hudi_fg_alias and (
hudi_fg_alias.left_feature_group_end_timestamp is not None
or hudi_fg_alias.left_feature_group_start_timestamp is not None
):
raise FeatureStoreException(
"Incremental queries are not supported in the python client."
+ " Read feature group without timestamp to retrieve latest snapshot or switch to "
+ "environment with Spark Engine."
)
def profile_by_spark(
self,
metadata_instance: Union[
FeatureGroup,
ExternalFeatureGroup,
feature_view.FeatureView,
TrainingDataset,
],
) -> job.Job:
stat_api = statistics_api.StatisticsApi(
metadata_instance.feature_store_id, metadata_instance.ENTITY_TYPE
)
job = stat_api.compute(metadata_instance)
print(
"Statistics Job started successfully, you can follow the progress at \n{}".format(
util.get_job_url(job.href)
)
)
job._wait_for_job()
return job
def profile(
self,
df: Union[pd.DataFrame, pl.DataFrame],
relevant_columns: List[str],
correlations: Any,
histograms: Any,
exact_uniqueness: bool = True,
) -> str:
# TODO: add statistics for correlations, histograms and exact_uniqueness
if HAS_POLARS and (
isinstance(df, pl.DataFrame) or isinstance(df, pl.dataframe.frame.DataFrame)
):
arrow_schema = df.to_arrow().schema
else:
arrow_schema = pa.Schema.from_pandas(df, preserve_index=False)
# parse timestamp columns to string columns
for field in arrow_schema:
if not (
pa.types.is_null(field.type)
or pa.types.is_list(field.type)
or pa.types.is_large_list(field.type)
or pa.types.is_struct(field.type)
) and PYARROW_HOPSWORKS_DTYPE_MAPPING.get(field.type, None) in [
"timestamp",
"date",
]:
if HAS_POLARS and (
isinstance(df, pl.DataFrame)
or isinstance(df, pl.dataframe.frame.DataFrame)
):
df = df.with_columns(pl.col(field.name).cast(pl.String))
else:
df[field.name] = df[field.name].astype(str)
if relevant_columns is None or len(relevant_columns) == 0:
stats = df.describe().to_dict()
relevant_columns = df.columns
else:
target_cols = [col for col in df.columns if col in relevant_columns]
stats = df[target_cols].describe().to_dict()
# df.describe() does not compute stats for all col types (e.g., string)
# we need to compute stats for the rest of the cols iteratively
missing_cols = list(set(relevant_columns) - set(stats.keys()))
for col in missing_cols:
stats[col] = df[col].describe().to_dict()
final_stats = []
for col in relevant_columns:
if HAS_POLARS and (
isinstance(df, pl.DataFrame)
or isinstance(df, pl.dataframe.frame.DataFrame)
):
stats[col] = dict(zip(stats["statistic"], stats[col]))
# set data type
arrow_type = arrow_schema.field(col).type
if (
pa.types.is_null(arrow_type)
or pa.types.is_list(arrow_type)
or pa.types.is_large_list(arrow_type)
or pa.types.is_struct(arrow_type)
or PYARROW_HOPSWORKS_DTYPE_MAPPING.get(arrow_type, None)
in ["timestamp", "date", "binary", "string"]
):
dataType = "String"
elif PYARROW_HOPSWORKS_DTYPE_MAPPING.get(arrow_type, None) in [
"float",
"double",
]:
dataType = "Fractional"
elif PYARROW_HOPSWORKS_DTYPE_MAPPING.get(arrow_type, None) in [
"int",
"bigint",
]:
dataType = "Integral"
elif PYARROW_HOPSWORKS_DTYPE_MAPPING.get(arrow_type, None) == "boolean":
dataType = "Boolean"
else:
print(
"Data type could not be inferred for column '"
+ col.split(".")[-1]
+ "'. Defaulting to 'String'",
file=sys.stderr,
)
dataType = "String"
stat = self._convert_pandas_statistics(stats[col], dataType)
stat["isDataTypeInferred"] = "false"
stat["column"] = col.split(".")[-1]
stat["completeness"] = 1
final_stats.append(stat)
return json.dumps(
{"columns": final_stats},
)
def _convert_pandas_statistics(
self, stat: Dict[str, Any], dataType: str
) -> Dict[str, Any]:
# For now transformation only need 25th, 50th, 75th percentiles
# TODO: calculate properly all percentiles
content_dict = {"dataType": dataType}
if "count" in stat:
content_dict["count"] = stat["count"]
if not dataType == "String":
if "25%" in stat:
percentiles = [0] * 100
percentiles[24] = stat["25%"]
percentiles[49] = stat["50%"]
percentiles[74] = stat["75%"]
content_dict["approxPercentiles"] = percentiles
if "mean" in stat:
content_dict["mean"] = stat["mean"]
if "mean" in stat and "count" in stat:
if isinstance(stat["mean"], numbers.Number):
content_dict["sum"] = stat["mean"] * stat["count"]
if "max" in stat:
content_dict["maximum"] = stat["max"]
if "std" in stat and not pd.isna(stat["std"]):
content_dict["stdDev"] = stat["std"]
if "min" in stat:
content_dict["minimum"] = stat["min"]
return content_dict
def validate(
self, dataframe: pd.DataFrame, expectations: Any, log_activity: bool = True
) -> None:
raise NotImplementedError(
"Deequ data validation is only available with Spark Engine. Use validate_with_great_expectations"
)
@uses_great_expectations
def validate_with_great_expectations(
self,
dataframe: Union[pl.DataFrame, pd.DataFrame],
expectation_suite: great_expectations.core.ExpectationSuite,
ge_validate_kwargs: Optional[Dict[Any, Any]] = None,
) -> great_expectations.core.ExpectationSuiteValidationResult:
# This conversion might cause a bottleneck in performance when using polars with greater expectations.
# This patch is done becuase currently great_expecatations does not support polars, would need to be made proper when support added.
if HAS_POLARS and (
isinstance(dataframe, pl.DataFrame)
or isinstance(dataframe, pl.dataframe.frame.DataFrame)
):
warnings.warn(
"Currently Great Expectations does not support Polars dataframes. This operation will convert to Pandas dataframe that can be slow.",
util.FeatureGroupWarning,
stacklevel=1,
)
dataframe = dataframe.to_pandas()
if ge_validate_kwargs is None:
ge_validate_kwargs = {}
report = great_expectations.from_pandas(
dataframe, expectation_suite=expectation_suite
).validate(**ge_validate_kwargs)
return report
def set_job_group(self, group_id: str, description: Optional[str]) -> None:
pass
def convert_to_default_dataframe(
self, dataframe: Union[pd.DataFrame, pl.DataFrame, pl.dataframe.frame.DataFrame]
) -> Optional[pd.DataFrame]:
if isinstance(dataframe, pd.DataFrame) or (
HAS_POLARS
and (
isinstance(dataframe, pl.DataFrame)
or isinstance(dataframe, pl.dataframe.frame.DataFrame)
)
):
upper_case_features = [
col for col in dataframe.columns if any(re.finditer("[A-Z]", col))
]
space_features = [col for col in dataframe.columns if " " in col]
# make shallow copy so the original df does not get changed
# this is always needed to keep the user df unchanged
if isinstance(dataframe, pd.DataFrame):
dataframe_copy = dataframe.copy(deep=False)
else:
dataframe_copy = dataframe.clone()
# making a shallow copy of the dataframe so that column names are unchanged
if len(upper_case_features) > 0:
warnings.warn(
"The ingested dataframe contains upper case letters in feature names: `{}`. "
"Feature names are sanitized to lower case in the feature store.".format(
upper_case_features
),
util.FeatureGroupWarning,
stacklevel=1,
)
if len(space_features) > 0:
warnings.warn(
"The ingested dataframe contains feature names with spaces: `{}`. "
"Feature names are sanitized to use underscore '_' in the feature store.".format(
space_features
),
util.FeatureGroupWarning,
stacklevel=1,
)
dataframe_copy.columns = [
util.autofix_feature_name(x) for x in dataframe_copy.columns
]
# convert timestamps with timezone to UTC
for col in dataframe_copy.columns:
if isinstance(
dataframe_copy[col].dtype, pd.core.dtypes.dtypes.DatetimeTZDtype
):
dataframe_copy[col] = dataframe_copy[col].dt.tz_convert(None)
elif HAS_POLARS and isinstance(dataframe_copy[col].dtype, pl.Datetime):
dataframe_copy = dataframe_copy.with_columns(
pl.col(col).dt.replace_time_zone(None)
)
return dataframe_copy
elif dataframe == "spine":
return None
raise TypeError(
"The provided dataframe type is not recognized. Supported types are: pandas dataframe, polars dataframe. "
+ "The provided dataframe has type: {}".format(type(dataframe))
)
def parse_schema_feature_group(
self,
dataframe: Union[pd.DataFrame, pl.DataFrame],
time_travel_format: Optional[str] = None,
features: Optional[List[feature.Feature]] = None,
) -> List[feature.Feature]:
feature_type_map = {}
if features:
for _feature in features:
feature_type_map[_feature.name] = _feature.type
if isinstance(dataframe, pd.DataFrame):
arrow_schema = pa.Schema.from_pandas(dataframe, preserve_index=False)
elif (
HAS_POLARS
and isinstance(dataframe, pl.DataFrame)
or isinstance(dataframe, pl.dataframe.frame.DataFrame)
):
arrow_schema = dataframe.to_arrow().schema
features = []
for i in range(len(arrow_schema.names)):
feat_name = arrow_schema.names[i]
name = util.autofix_feature_name(feat_name)
try:
pd_type = arrow_schema.field(feat_name).type
if pa.types.is_null(pd_type) and feature_type_map.get(name):
converted_type = feature_type_map.get(name)
else:
converted_type = convert_pandas_dtype_to_offline_type(pd_type)
except ValueError as e:
raise FeatureStoreException(f"Feature '{name}': {str(e)}") from e
features.append(feature.Feature(name, converted_type))
return features
def parse_schema_training_dataset(
self, dataframe: Union[pd.DataFrame, pl.DataFrame]
) -> List[feature.Feature]:
raise NotImplementedError(
"Training dataset creation from Dataframes is not "
+ "supported in Python environment. Use HSFS Query object instead."
)
def save_dataframe(
self,
feature_group: FeatureGroup,
dataframe: Union[pd.DataFrame, pl.DataFrame],
operation: str,
online_enabled: bool,
storage: str,
offline_write_options: Dict[str, Any],
online_write_options: Dict[str, Any],
validation_id: Optional[int] = None,
) -> Optional[job.Job]:
# Currently on-demand transformation functions not supported in external feature groups.
if (
not isinstance(feature_group, ExternalFeatureGroup)
and feature_group.transformation_functions
):
dataframe = self._apply_transformation_function(
feature_group.transformation_functions, dataframe
)
if (
hasattr(feature_group, "EXTERNAL_FEATURE_GROUP")
and feature_group.online_enabled
) or feature_group.stream:
return self._write_dataframe_kafka(
feature_group, dataframe, offline_write_options
)
else:
# for backwards compatibility
return self.legacy_save_dataframe(
feature_group,
dataframe,
operation,
online_enabled,
storage,
offline_write_options,
online_write_options,
validation_id,
)
def legacy_save_dataframe(
self,
feature_group: FeatureGroup,
dataframe: Union[pd.DataFrame, pl.DataFrame],
operation: str,
online_enabled: bool,
storage: str,
offline_write_options: Dict[str, Any],
online_write_options: Dict[str, Any],
validation_id: Optional[int] = None,
) -> Optional[job.Job]:
# App configuration
app_options = self._get_app_options(offline_write_options)
# Setup job for ingestion
# Configure Hopsworks ingestion job
print("Configuring ingestion job...")
ingestion_job = self._feature_group_api.ingestion(feature_group, app_options)
# Upload dataframe into Hopsworks
print("Uploading Pandas dataframe...")
self._dataset_api.upload_feature_group(
feature_group, ingestion_job.data_path, dataframe
)
# run job
ingestion_job.job.run(
await_termination=offline_write_options is None
or offline_write_options.get("wait_for_job", True)
)
return ingestion_job.job
def get_training_data(
self,
training_dataset_obj: TrainingDataset,
feature_view_obj: feature_view.FeatureView,
query_obj: query.Query,
read_options: Dict[str, Any],
dataframe_type: str,
training_dataset_version: int = None,
) -> Union[pd.DataFrame, pl.DataFrame]:
"""
Function that creates or retrieves already created the training dataset.
# Arguments
training_dataset_obj `TrainingDataset`: The training dataset metadata object.
feature_view_obj `FeatureView`: The feature view object for the which the training data is being created.
query_obj `Query`: The query object that contains the query used to create the feature view.
read_options `Dict[str, Any]`: Dictionary that can be used to specify extra parameters for reading data.
dataframe_type `str`: The type of dataframe returned.
training_dataset_version `int`: Version of training data to be retrieved.
# Raises
`ValueError`: If the training dataset statistics could not be retrieved.
"""
# dataframe_type of list and numpy are prevented here because statistics needs to be computed from the returned dataframe.
# The daframe is converted into required types in the function split_labels
if dataframe_type.lower() not in ["default", "polars", "pandas"]:
dataframe_type = "default"
if training_dataset_obj.splits:
return self._prepare_transform_split_df(
query_obj,
training_dataset_obj,
feature_view_obj,
read_options,
dataframe_type,
training_dataset_version,
)
else:
df = query_obj.read(
read_options=read_options, dataframe_type=dataframe_type
)
# if training_dataset_version is None:
transformation_function_engine.TransformationFunctionEngine.compute_and_set_feature_statistics(
training_dataset_obj, feature_view_obj, df
)
# else:
# transformation_function_engine.TransformationFunctionEngine.get_and_set_feature_statistics(
# training_dataset_obj, feature_view_obj, training_dataset_version
# )
return self._apply_transformation_function(
feature_view_obj.transformation_functions, df
)
def split_labels(
self,
df: Union[pd.DataFrame, pl.DataFrame],
labels: List[str],
dataframe_type: str,
) -> Tuple[
Union[pd.DataFrame, pl.DataFrame], Optional[Union[pd.DataFrame, pl.DataFrame]]
]:
if labels:
labels_df = df[labels]
df_new = df.drop(columns=labels)
return (
self._return_dataframe_type(df_new, dataframe_type),
self._return_dataframe_type(labels_df, dataframe_type),
)
else:
return self._return_dataframe_type(df, dataframe_type), None
def drop_columns(
self, df: Union[pd.DataFrame, pl.DataFrame], drop_cols: List[str]
) -> Union[pd.DataFrame, pl.DataFrame]:
return df.drop(columns=drop_cols)
def _prepare_transform_split_df(
self,
query_obj: query.Query,
training_dataset_obj: TrainingDataset,
feature_view_obj: feature_view.FeatureView,
read_option: Dict[str, Any],
dataframe_type: str,
training_dataset_version: int = None,
) -> Dict[str, Union[pd.DataFrame, pl.DataFrame]]:
"""
Split a df into slices defined by `splits`. `splits` is a `dict(str, int)` which keys are name of split
and values are split ratios.
# Arguments
query_obj `Query`: The query object that contains the query used to create the feature view.
training_dataset_obj `TrainingDataset`: The training dataset metadata object.
feature_view_obj `FeatureView`: The feature view object for the which the training data is being created.
read_options `Dict[str, Any]`: Dictionary that can be used to specify extra parameters for reading data.
dataframe_type `str`: The type of dataframe returned.
training_dataset_version `int`: Version of training data to be retrieved.
# Raises
`ValueError`: If the training dataset statistics could not be retrieved.
"""
if (
training_dataset_obj.splits[0].split_type
== TrainingDatasetSplit.TIME_SERIES_SPLIT
):
event_time = query_obj._left_feature_group.event_time
if event_time not in [_feature.name for _feature in query_obj.features]:
query_obj.append_feature(
query_obj._left_feature_group.__getattr__(event_time)
)
result_dfs = self._time_series_split(
query_obj.read(
read_options=read_option, dataframe_type=dataframe_type
),
training_dataset_obj,
event_time,
drop_event_time=True,
)
else:
result_dfs = self._time_series_split(
query_obj.read(
read_options=read_option, dataframe_type=dataframe_type
),
training_dataset_obj,
event_time,
)
else:
result_dfs = self._random_split(
query_obj.read(read_options=read_option, dataframe_type=dataframe_type),
training_dataset_obj,
)