-
Notifications
You must be signed in to change notification settings - Fork 3
/
io_services.py
1096 lines (873 loc) · 35.7 KB
/
io_services.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
import os
from typing import Any
from pathlib import Path
import logging
import json
import warnings
import pandas as pd
import duckdb
import pickle
from google.cloud import storage
from abstract import AbstractInputReader, AbstractOutputWriter, AbstractIOProcessor
# suppress unrelated warnings
warnings.filterwarnings("ignore")
class BaseIOReaderWriter:
def __init__(self):
pass
@property
def __str__(self):
bases = [base.__name__ for base in self.__class__.__bases__]
bases.append(self.__class__.__name__)
return ".".join(bases)
class BaseInputReader(AbstractInputReader, BaseIOReaderWriter):
def __init__(self):
super().__init__()
class BaseOutputWriter(AbstractOutputWriter, BaseIOReaderWriter):
def __init__(self):
super().__init__()
class BaseIOProcessor(AbstractIOProcessor):
def __init__(self):
super().__init__()
@property
def __str__(self):
bases = [base.__name__ for base in self.__class__.__bases__]
bases.append(self.__class__.__name__)
return ".".join(bases)
class LocalInputReader(BaseInputReader):
"""
:param method: *(Required)* Source type to read from.\n
Parameters choices: ['db', 'filesystem']
:type method: str
:param input_path: *(Required)* Path to a source file or a local db file
:type input_path: str
:param init_script_path: *(Optional)* Path to initial script for database initialization
:type init_script_path: str
:param init_data_path: *(Optional)* Path to initial data path for database initialization
:type init_data_path: str
"""
def __init__(
self,
method: str,
exec_date: str,
input_path: str,
output_path: str,
init_script_path: str = "db/sql/init_sales.sql",
init_data_path: str = "../../data/ecomm_invoice_transaction.parquet",
*args,
**kwargs,
):
super().__init__()
self.method = method
self.exec_date = exec_date #TODO: implement local input path partition
self.input_path = Path(input_path)
self.output_path = Path(output_path)
# sql_path
# data_model
self.init_script_path = init_script_path
self.init_data_path = init_data_path
if method == "db":
if self.is_db_exists(input_path):
logging.info("Input database exists, no initialization required")
else:
logging.info("Input database not exists, method 'db', initializing db...")
self.init_db()
elif method == "filesystem":
logging.warning(
"method 'filesystem', no initialization required"
)
else:
raise Exception(
"Database is not exist. Unacceptable `method` argument for Reader."
)
@staticmethod
def is_db_exists(input_path: str) -> bool:
# os.path.isfile(path=input_path) -> bool
data_file = Path(input_path)
return data_file.is_file()
@staticmethod
def connect_db(input_path: str) -> tuple:
con = duckdb.connect(input_path)
cursor = con.cursor()
return (cursor, con)
@staticmethod
def render_sql(file_path: str) -> str:
with open(file_path, "r") as sql_f:
statement = sql_f.read()
sql_f.close()
return statement
def init_db(self) -> None:
# connect local db
cursor, con = self.connect_db(path=self.input_path)
# read initial script
statement = self.render_sql(self.init_script_path)
# execute sql
sql_params = {
"data_model": "ecomm_gold.sales_transaction", # only sales data is acceptable for initialization
"data_path": self.init_data_path,
}
cursor.execute(statement, parameters=sql_params)
# .execute() return connection
# .sql() return relation (table)
con.close()
def read_data(self, input_path: Path):
logging.info(f"Reading data file: {input_path.name}")
# Path().stem, Path().suffix, Path().name, Path().parent
df = pd.read_parquet(input_path)
logging.info(f"Successfully read data file: {input_path.name}")
return df
def is_model_exist(
self,
model_path: str | Path,
model_name: str = None
) -> bool:
"""
Check if interpreter is available
Return
------
- is_model_exist flag
- path to model if exists with latest version (None if no model exists)
"""
model_files = self.list_model_in_path(
model_path=model_path,
model_name=model_name
)
if len(model_files) != 0:
return True
else:
return False
@staticmethod
def list_model_in_path(
model_path: str | Path,
model_name: str = None
) -> list[str]:
"""
List models in the specified folder
"""
files = os.listdir(model_path)
if model_name is not None:
model_files = [file for file in files if model_name in file]
else:
model_files = files
return model_files
def find_latest_model(
self,
model_path: str | Path,
model_name: str
) -> Path | None:
"""
Find the latest model version path with specified model name
"""
model_files = self.list_model_in_path(
model_path=model_path,
model_name=model_name
)
if len(model_files) != 0:
# retrieve the latest model version as a name
latest_model = Path(max(model_files))
return latest_model
else:
return None
def read_interpreter(self, output_path: Path) -> Any:
"""
Read interpreter model with pickle
Return
------
Model: Any
"""
model_path = output_path / "models"
logging.info(f"Searching for Interpreter Model from: {model_path}")
# create folder if not exist
model_path.mkdir(parents=True, exist_ok=True)
if self.is_model_exist(model_path=model_path, model_name="interpreter"):
logging.info("Interpreter is available, Read Interpreter...")
# find latest version
latest_mdoel = self.find_latest_model(
model_path=model_path,
model_name="interpreter"
)
logging.info(f"Found the latest model as: {latest_mdoel}")
# read model with pickle
with open(model_path / latest_mdoel, "rb") as f:
interpreter = pickle.load(f)
f.close()
logging.info("Successfully Read Interpreter")
else:
logging.info("Interpreter is not available, Skipped")
interpreter = None
return interpreter
def read(self, sql_path: str = None, sql_params: dict = None) -> pd.DataFrame:
if self.method == "db":
# logging.info(f"Reading db path from: {self.input_path}")
# # connect db
# cursor, con = self.connect_db(path=sql_path)
# # execute reading input statement, then load to pandas dataframe
# statement = self.render_sql(sql_path)
# df = cursor.sql(statement, parameters=sql_params).to_df()
# con.close()
# return df
raise Exception("Method 'db' is not implemented yet.")
elif self.method == "filesystem":
logging.info(f"Reading filesystem path from: {self.input_path}")
# reading data
df = self.read_data(input_path=self.input_path)
# interpreter
interpreter = self.read_interpreter(output_path=self.output_path)
# formulate input for model services
inputs: dict = {
"df": df,
"interpreter": interpreter
}
return inputs
else:
raise Exception("Unacceptable `method` argument for Reader.")
class GCPInputReader(BaseInputReader):
def __init__(
self,
method: str,
project_id: str,
exec_date: str,
input_path: str,
output_path: str,
*args,
**kwargs,
):
super().__init__()
self.method = method
self.project_id = project_id
self.exec_date = exec_date
self.input_path = input_path
self.output_path = output_path
if method == "db":
if self.is_db_exists(input_path):
logging.info("Input database exists")
else:
raise Exception("Database or dataset is not exist")
elif method == "filesystem":
# validate uri format
is_input_path_valid, is_output_path_valid = self.is_uri_valid(
input_path=self.input_path,
output_path=self.output_path
)
if is_input_path_valid and is_output_path_valid:
logging.info("input_path and output_path are valid.")
else:
raise Exception("Either input_path or output_path is invalid format. (gs://) is required.")
else:
raise Exception(
"Database is not exist. Unacceptable `method` argument for Reader."
)
@staticmethod
def is_db_exists():
# TODO: implement db method
pass
@staticmethod
def connect_db():
# TODO: implement db method
pass
@staticmethod
def render_sql(file_path: str) -> str:
pass
@staticmethod
def is_uri_valid(input_path: str, output_path: str) -> bool:
"""Verify URI input"""
# input_path
input_parts = input_path.split("/")
if ("gs:" in input_parts) and (len(input_parts) >= 3):
is_input_path_valid = True
else:
is_input_path_valid = False
# output
output_parts = output_path.split("/")
if ("gs:" in output_parts) and (len(output_parts) >= 3):
is_output_path_valid = True
else:
is_output_path_valid = False
return is_input_path_valid, is_output_path_valid
def read_data(self, input_path: str):
"""
Read Data from specified path
:input_path params: 'gs://{bucket}/{prefix}'
:input_path Path:
"""
file_name = input_path.split("/")[-1]
logging.info(f"Reading data file: {file_name}")
# Path().stem, Path().suffix, Path().name, Path().parent, Path().parts
df = pd.read_parquet(input_path)
logging.info(f"Successfully read data file: {file_name}")
return df
def list_model_in_path(self, model_path: str, model_name: str = None) -> list[str]:
"""
List models in the specified folder
"""
# get components
bucket_name = model_path.split("/")[2]
prefix_name = "/".join(model_path.split("/")[3:])
storage_client = storage.Client(project=self.project_id)
blobs = storage_client.list_blobs(
bucket_or_name=bucket_name,
prefix=prefix_name
)
blobs_list = list(blobs)
if model_name is not None:
model_files = [file.name for file in blobs_list if model_name in file.name]
else:
model_files = blobs_list
return model_files
def is_model_exist(self, model_path: str, model_name: str = None) -> bool:
"""
Check if interpreter is available
Return
------
- is_model_exist flag
- path to model if exists with latest version (None if no model exists)
"""
model_files = self.list_model_in_path(
model_path=model_path,
model_name=model_name
)
if len(model_files) != 0:
return True
else:
return False
def find_latest_model(
self,
model_path: str,
model_name: str
) -> str | None:
"""
Find the latest model version path with specified model name
"""
model_files = self.list_model_in_path(
model_path=model_path,
model_name=model_name
)
if len(model_files) != 0:
# retrieve the latest model version as a name
latest_model = max(model_files)
return latest_model
else:
return None
def read_model_blob(self, path: str):
bucket_name = path.split("/")[2]
target_path = "/".join(path.split("/")[3:])
storage_client = storage.Client(project=self.project_id)
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(target_path)
with blob.open("rb") as f:
model = pickle.load(f)
f.close()
return model
def read_interpreter(self, output_path: str) -> Any:
"""
Read interpreter model with pickle
Return
------
Model: Any
"""
logging.info(f"Searching for Interpreter Model from: {output_path}")
model_path = f"{output_path}/models"
if self.is_model_exist(model_path=model_path, model_name="interpreter"):
logging.info("Interpreter is available, Read Interpreter...")
# find latest version
latest_mdoel = self.find_latest_model(
model_path=model_path,
model_name="interpreter"
)
logging.info(f"Found the latest model as: {latest_mdoel}")
# re-structure uri
bucket_name = model_path.split("/")[2]
model_path = f"gs://{bucket_name}/{latest_mdoel}"
# read model with pickle
interpreter = self.read_model_blob(path=model_path)
logging.info("Successfully Read Interpreter")
else:
logging.info("Interpreter is not available, Skipped")
interpreter = None
return interpreter
def read(self, sql_path: str = None, sql_params: dict = None) -> pd.DataFrame:
if self.method == "db":
# logging.info(f"Reading db path from: {self.input_path}")
# # connect db
# cursor, con = self.connect_db(path=sql_path)
# # execute reading input statement, then load to pandas dataframe
# statement = self.render_sql(sql_path)
# df = cursor.sql(statement, parameters=sql_params).to_df()
# con.close()
# return df
raise Exception("Method 'db' is not implemented yet.")
elif self.method == "filesystem":
logging.info(f"Reading filesystem path from: {self.input_path}")
# reading data
df = self.read_data(input_path=self.input_path)
# interpreter
interpreter = self.read_interpreter(output_path=self.output_path)
# formulate input for model services
inputs: dict = {
"df": df,
"interpreter": interpreter
}
return inputs
else:
raise Exception("Unacceptable `method` argument for Reader.")
class APIInputReader(BaseInputReader):
pass
class InputProcessor(BaseIOProcessor):
"""
Entrypoint for InputReader instance, selecting connection/environment type by given parameters.
"""
def __init__(
self,
env: str,
method: str,
exec_date: str,
input_path: str = None,
output_path: str = None,
project_id: str = None
):
self.env = env
self.method = method
self.project_id = project_id
self.exec_date = exec_date
self.input_path = input_path
self.output_path = output_path
self.factory = {
"local": LocalInputReader,
"postgresql": APIInputReader,
"gcp": GCPInputReader,
}
def process(self):
logging.info(f"Input Processor: {self.__str__}")
reader_instance = self.factory.get(self.env)
reader_args = {
"method": self.method,
"project_id": self.project_id,
"exec_date": self.exec_date,
"input_path": self.input_path,
"output_path": self.output_path
}
reader = reader_instance(**reader_args)
logging.info(f"Selected reader: {reader.__str__}")
logging.info(f"Reader arguments: {reader_args}")
if reader_instance:
return reader.read()
else:
raise Exception("No InputReader assigned in InputProcessor factory")
class LocalOutputWriter(BaseOutputWriter):
def __init__(
self,
method: str,
output_path: str,
exec_date: str,
output: dict,
*args,
**kwargs
) -> None:
super().__init__()
self.method = method
self.output_path = Path(output_path)
self.exec_date = exec_date
self.output = output
def build_control_file_dict(self, artifacts: dict[str, Any]) -> dict:
control_file_dict: dict = {}
control_file_dict["interpreter_params"] = artifacts.get("interpreter_params")
control_file_dict["interpreter_metrics"] = artifacts.get("interpreter_metrics")
control_file_dict["is_train_interpreter"] = artifacts.get("is_train_interpreter")
control_file_dict["is_anomaly_exist"] = artifacts.get("is_anomaly_exist")
return control_file_dict
def find_latest_model_version(
self,
model_path: str | Path,
model_name: str
) -> int:
latest_model = self.find_latest_model(
model_path=model_path,
model_name=model_name
)
latest_version = Path(latest_model).name.split("_v")[-1]
return latest_version
def write_element(
self,
output: Any,
element_type: str,
filename: str
) -> None:
"""
Writing output file depends on arguments
Parameters
----------
- output: pd.DataFrame | KMeans | LGBMClassifier | dict
- element_type: str
- filename: str
"""
if element_type == "data":
# prep filename and path
data_file_name = f"{str(filename)}.parquet"
# date = datetime.today().date().strftime("%Y-%m-%d")
data_path = self.output_path / "data" / self.exec_date
# create directory if not exist
data_path.mkdir(parents=True, exist_ok=True)
# export
output.to_parquet(data_path / data_file_name)
# logs
logging.info(f"Successfully export data to {str(data_path / data_file_name)}")
elif element_type == "model":
# prep path
model_path = self.output_path / "models"
# create directory if not exist
model_path.mkdir(parents=True, exist_ok=True)
# dynamic bump model version if available
files = os.listdir(model_path)
model_files = [file for file in files if file.startswith(filename)]
if len(model_files) != 0:
version = int(Path(max(model_files)).stem.split("_v")[1]) + 1
else:
version = 1
# prep filename and path
model_file_name = f"{filename}_v{version}.pkl"
model_path = model_path / model_file_name
# export
with open(model_path, "+wb") as f:
pickle.dump(output, f)
f.close()
# logs
logging.info(f"Successfully export model to {str(model_path / model_file_name)}")
elif element_type == "artifact":
# aka control file as json
# prep filename and path
artifact_file_name = f"{filename}.json"
artifact_path = self.output_path / "artifact" / self.exec_date
# create directory if not exist
artifact_path.mkdir(parents=True, exist_ok=True)
# export
with open(artifact_path / artifact_file_name, "+w") as f:
json.dump(output, f, indent=4)
f.close()
# anomaly cluster flag (revert)
# if output.get("is_anomaly_exist"):
# with open(artifact_path / "ANOMALY_EXIST", "w") as f:
# f.close()
# logging.info(f"Successfully export anomaly flag file (artifact) to {artifact_path / 'ANOMALY_EXIST'}")
# logs
logging.info(f"Successfully export control file (artifact) to {str(artifact_path / artifact_file_name)}")
def write(self, sql_path: str = None, sql_params: dict = None) -> None:
if self.method == "db":
# connect db
cursor, con = self.connect_db(path=self.output_path)
# reading sql file rendering sql statement
statement = self.render_sql(file_path=sql_path)
# execute writing output statement to load pandas DataFrame to duckdb database
# https://duckdb.org/docs/guides/python/import_pandas.html
in_memory_df = self.df
in_memory_df_param = "in_memory_df"
sql_params = {**sql_params, in_memory_df_param: in_memory_df}
cursor.sql(statement, parameters=sql_params)
con.close()
logging.info(
f"Successfully write output file: {Path(self.output_path).name}"
)
return 1
elif self.method == "filesystem":
# writing file
logging.info(f"Writing file to: {Path(self.output_path)}")
# data model
logging.info("Exporting... Data Models")
df_cluster_rfm: pd.DataFrame = self.output.get("df_cluster_rfm")
df_cluster_importance: pd.DataFrame = self.output.get("df_cluster_importance")
self.write_element(output=df_cluster_rfm, element_type="data", filename="df_cluster_rfm")
self.write_element(output=df_cluster_importance, element_type="data", filename="df_cluster_importance")
# ml model
logging.info("Exporting... ML Models")
segmenter_trained = self.output.get("segmenter_trained")
segmenter_scaler = self.output.get("segmenter_scaler")
interpreter = self.output.get("interpreter")
self.write_element(output=segmenter_trained, element_type="model", filename="kmeans_segmenter")
self.write_element(output=segmenter_scaler, element_type="model", filename="segmenter_scaler")
self.write_element(output=interpreter, element_type="model", filename="lgbm_interpreter")
# other artifacts
logging.info("Exporting... Artifact (Control file)")
# aggregate artifact
artifacts = {
"interpreter_params": self.output.get("interpreter_params"),
"interpreter_metrics": self.output.get("interpreter_metrics"),
"is_train_interpreter": self.output.get("is_train_interpreter"), # boolean,
# "latest_trained_model_version": self.find_latest_model_version(model_path=), #TODO: solve this logic finding the latest trained model version
"is_anomaly_exist": self.output.get("is_anomaly_exist") # boolean
}
control_file_dict = self.build_control_file_dict(artifacts=artifacts)
self.write_element(output=control_file_dict, element_type="artifact", filename="control_file")
else:
raise Exception("Unacceptable `method` argument for Reader.")
class GCPOutputWriter(BaseOutputWriter):
def __init__(
self,
method: str,
project_id: str,
output_path: str,
exec_date: str,
output: dict,
) -> None:
super().__init__()
self.method = method
self.project_id = project_id
self.output_path = output_path
self.exec_date = exec_date
self.output = output
def build_control_file_dict(self, artifacts: dict[str, Any]) -> dict:
control_file_dict: dict = {}
control_file_dict["interpreter_params"] = artifacts.get("interpreter_params")
control_file_dict["interpreter_metrics"] = artifacts.get("interpreter_metrics")
control_file_dict["is_train_interpreter"] = artifacts.get("is_train_interpreter")
control_file_dict["is_anomaly_exist"] = artifacts.get("is_anomaly_exist")
return control_file_dict
def list_model_in_path(self, model_path: str, model_name: str = None) -> list[str]:
"""
List models in the specified folder
"""
# get components
bucket_name = model_path.split("/")[2]
prefix_name = "/".join(model_path.split("/")[3:])
storage_client = storage.Client(project=self.project_id)
blobs = storage_client.list_blobs(
bucket_or_name=bucket_name,
prefix=prefix_name
)
blobs_list = list(blobs)
if model_name is not None:
model_files = [file.name for file in blobs_list if model_name in file.name]
else:
model_files = blobs_list
return model_files
def find_latest_model(
self,
model_path: str,
model_name: str
) -> Path | None:
"""
Find the latest model version path with specified model name
"""
model_files = self.list_model_in_path(
model_path=model_path,
model_name=model_name
)
if len(model_files) != 0:
# retrieve the latest model version as a name
latest_model = max(model_files)
return latest_model
else:
return None
def find_latest_model_version(
self,
model_path: str,
model_name: str
) -> int:
latest_model: str = self.find_latest_model(
model_path=model_path,
model_name=model_name
)
latest_version = latest_model.split("/")[-1].split("_v")[-1].split(".")[0]
return int(latest_version)
def is_model_exist(self, model_path: str, model_name: str = None) -> bool:
"""
Check if interpreter is available
Return
------
- is_model_exist flag
- path to model if exists with latest version (None if no model exists)
"""
model_files = self.list_model_in_path(
model_path=model_path,
model_name=model_name
)
if len(model_files) != 0:
return True
else:
return False
def write_blob(self, path: str, output: Any, how: str) -> None:
"""
Upload output element (model/json file) to GCS
:param path: exact path to target
:type path: Path
:param model: output element
:type model: Any
:param how: ['pickle', 'json']
:type how: str
"""
bucket_name = path.split("/")[2]
target_path = "/".join(path.split("/")[3:])
storage_client = storage.Client(project=self.project_id)
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(target_path)
if how == "pickle": # binary
with blob.open("wb") as f:
pickle.dump(output, f)
f.close()
elif how == "json":
with blob.open("w") as f:
json.dump(output, f, indent=4)
f.close()
elif how == "none":
blob.upload_from_string("")
else:
raise Exception("'how' parameter is not valid.")
def write_element(
self,
output: Any,
element_type: str,
filename: str
) -> None:
"""
Writing output file depends on arguments
Parameters
----------
- output: pd.DataFrame | KMeans | LGBMClassifier | dict
- element_type: str
- filename: str
"""
if element_type == "data":
# prep filename and path
data_file_name = f"{str(filename)}.parquet"
# date = datetime.today().date().strftime("%Y-%m-%d")
data_path = f"{self.output_path}/data/{self.exec_date}/{data_file_name}"
# export
output.to_parquet(data_path)
# logs
logging.info(f"Successfully export data to {data_path}")
elif element_type == "model":
# prep path
model_path = f"{self.output_path}/models"
# dynamic bump model version if available
if self.is_model_exist(model_path=model_path, model_name="interpreter"):
latest_version = self.find_latest_model_version(model_path=model_path, model_name=filename)
version = latest_version + 1
else:
version = 1
# prep filename and path
model_file_name = f"{filename}_v{version}.pkl"
model_path = f"{model_path}/{model_file_name}"
# export
self.write_blob(path=model_path, output=output, how="pickle")
# logs
logging.info(f"Successfully export model to {model_path}")
elif element_type == "artifact":
# aka control file as json
# prep filename and path
artifact_file_name = f"{filename}.json"
# artifact_flag_path = f"{self.output_path}/artifact/{self.exec_date}/ANOMALY_EXIST"
artifact_path = f"{self.output_path}/artifact/{self.exec_date}/{artifact_file_name}"
# export
self.write_blob(path=artifact_path, output=output, how="json")
# anomaly cluster flag
# if output.get("is_anomaly_exist"):
# self.write_blob(path=artifact_flag_path, output=None, how="none")
# logging.info(f"Successfully export anomaly flag file (artifact) to {artifact_flag_path}")
# logs
logging.info(f"Successfully export control file (artifact) to {artifact_path}")
def write(self, sql_path: str = None, sql_params: dict = None) -> None:
if self.method == "db":
# TODO: implement db method
# # connect db
# cursor, con = self.connect_db(path=self.output_path)
# # reading sql file rendering sql statement
# statement = self.render_sql(file_path=sql_path)
# # execute writing output statement to load pandas DataFrame to duckdb database
# # https://duckdb.org/docs/guides/python/import_pandas.html
# in_memory_df = self.df
# in_memory_df_param = "in_memory_df"
# sql_params = {**sql_params, in_memory_df_param: in_memory_df}
# cursor.sql(statement, parameters=sql_params)
# con.close()
# logging.info(
# f"Successfully write output file: {Path(self.output_path).name}"
# )
# return 1
pass
elif self.method == "filesystem":
# writing file
logging.info(f"Writing file to: {Path(self.output_path)}")
# data model
logging.info("Exporting... Data Models")
df_cluster_rfm: pd.DataFrame = self.output.get("df_cluster_rfm")
df_cluster_importance: pd.DataFrame = self.output.get("df_cluster_importance")
self.write_element(output=df_cluster_rfm, element_type="data", filename="df_cluster_rfm")
self.write_element(output=df_cluster_importance, element_type="data", filename="df_cluster_importance")
# ml model
logging.info("Exporting... ML Models")