Repository navigation
Expand file tree
/
Copy pathpipeline_component_library.with_texts.yaml
More file actions
8447 lines (7780 loc) · 413 KB
/
Copy pathpipeline_component_library.with_texts.yaml
File metadata and controls
8447 lines (7780 loc) · 413 KB
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
annotations: {}
folders:
- name: Quick start
components:
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/57f780b15922061e59833541b71f3d099e710177/components/datasets/Chicago_Taxi_Trips/quick_start_version/component.yaml
digest: 42030acab16b71bbc3ad018563b5aedb94d373e72f7cb2b322bc27dbbee75e1b
text: |
name: Chicago Taxi Trips dataset
description: |
City of Chicago Taxi Trips dataset: https://data.cityofchicago.org/Transportation/Taxi-Trips/wrvz-psew
The input parameters configure the SQL query to the database.
The dataset is pretty big, so limit the number of results using the `Limit` or `Where` parameters.
Read [Socrata dev](https://dev.socrata.com/docs/queries/) for the advanced query syntax
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/datasets/Chicago_Taxi_Trips/quick_start_version/component.yaml'
inputs:
- {name: Where, type: String, default: 'trip_start_timestamp>="1900-01-01" AND trip_start_timestamp<"2100-01-01"'}
- {name: Limit, type: Integer, default: '1000', description: 'Number of rows to return. The rows are randomly sampled.'}
- {name: Select, type: String, default: 'tips,trip_seconds,trip_miles,pickup_community_area,dropoff_community_area,fare,tolls,extras,trip_total'}
- {name: Format, type: String, default: 'csv', description: 'Output data format. Supports csv,tsv,cml,rdf,json'}
outputs:
- {name: Table, description: 'Result type depends on format. CSV and TSV have header.'}
implementation:
container:
# image: curlimages/curl # Sets a non-root user which cannot write to mounted volumes. See https://github.com/curl/curl-docker/issues/22
image: alpine/curl:8.14.1
command:
- sh
- -c
- |
set -e -x -o pipefail
output_path="$0"
select="$1"
where="$2"
limit="$3"
format="$4"
mkdir -p "$(dirname "$output_path")"
curl --get 'https://data.cityofchicago.org/resource/wrvz-psew.'"${format}" \
--data-urlencode '$limit='"${limit}" \
--data-urlencode '$where='"${where}" \
--data-urlencode '$select='"${select}" \
| sed -E 's/"([^",\]*)"/\1/g' > "$output_path" # Removing unneeded quotes around all numbers
- {outputPath: Table}
- {inputValue: Select}
- {inputValue: Where}
- {inputValue: Limit}
- {inputValue: Format}
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/96a177dd71d54c98573c4101d9a05ac801f1fa54/components/XGBoost/Train/component.yaml
digest: 5b8bec6716337d7bd8ecafd6dd46bc44527783bc05950cfe03a60206b43c7654
text: |
name: Train XGBoost model on CSV
description: Trains an XGBoost model.
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/XGBoost/Train/component.yaml'}
inputs:
- {name: training_data, type: CSV, description: Training data in CSV format.}
- {name: label_column_name, type: String, description: Name of the column containing
the label data.}
- {name: starting_model, type: XGBoostModel, description: Existing trained model to
start from (in the binary XGBoost format)., optional: true}
- {name: num_iterations, type: Integer, description: Number of boosting iterations.,
default: '10', optional: true}
- name: objective
type: String
description: |-
The learning task and the corresponding learning objective.
See https://xgboost.readthedocs.io/en/latest/parameter.html#learning-task-parameters
The most common values are:
"reg:squarederror" - Regression with squared loss (default).
"reg:logistic" - Logistic regression.
"binary:logistic" - Logistic regression for binary classification, output probability.
"binary:logitraw" - Logistic regression for binary classification, output score before logistic transformation
"rank:pairwise" - Use LambdaMART to perform pairwise ranking where the pairwise loss is minimized
"rank:ndcg" - Use LambdaMART to perform list-wise ranking where Normalized Discounted Cumulative Gain (NDCG) is maximized
default: reg:squarederror
optional: true
- {name: booster, type: String, description: 'The booster to use. Can be `gbtree`,
`gblinear` or `dart`; `gbtree` and `dart` use tree based models while `gblinear`
uses linear functions.', default: gbtree, optional: true}
- {name: learning_rate, type: Float, description: 'Step size shrinkage used in update
to prevents overfitting. Range: [0,1].', default: '0.3', optional: true}
- name: min_split_loss
type: Float
description: |-
Minimum loss reduction required to make a further partition on a leaf node of the tree.
The larger `min_split_loss` is, the more conservative the algorithm will be. Range: [0,Inf].
default: '0'
optional: true
- name: max_depth
type: Integer
description: |-
Maximum depth of a tree. Increasing this value will make the model more complex and more likely to overfit.
0 indicates no limit on depth. Range: [0,Inf].
default: '6'
optional: true
- {name: booster_params, type: JsonObject, description: 'Parameters for the booster.
See https://xgboost.readthedocs.io/en/latest/parameter.html', optional: true}
outputs:
- {name: model, type: XGBoostModel, description: Trained model in the binary XGBoost
format.}
- {name: model_config, type: XGBoostModelConfig, description: The internal parameter
configuration of Booster as a JSON string.}
implementation:
container:
image: python:3.10
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'xgboost==1.6.1' 'pandas==1.4.3' 'numpy<2' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'xgboost==1.6.1' 'pandas==1.4.3' 'numpy<2'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def train_XGBoost_model_on_CSV(
training_data_path,
model_path,
model_config_path,
label_column_name,
starting_model_path = None,
num_iterations = 10,
# Booster parameters
objective = "reg:squarederror",
booster = "gbtree",
learning_rate = 0.3,
min_split_loss = 0,
max_depth = 6,
booster_params = None,
):
"""Trains an XGBoost model.
Args:
training_data_path: Training data in CSV format.
model_path: Trained model in the binary XGBoost format.
model_config_path: The internal parameter configuration of Booster as a JSON string.
starting_model_path: Existing trained model to start from (in the binary XGBoost format).
label_column_name: Name of the column containing the label data.
num_iterations: Number of boosting iterations.
booster_params: Parameters for the booster. See https://xgboost.readthedocs.io/en/latest/parameter.html
objective: The learning task and the corresponding learning objective.
See https://xgboost.readthedocs.io/en/latest/parameter.html#learning-task-parameters
The most common values are:
"reg:squarederror" - Regression with squared loss (default).
"reg:logistic" - Logistic regression.
"binary:logistic" - Logistic regression for binary classification, output probability.
"binary:logitraw" - Logistic regression for binary classification, output score before logistic transformation
"rank:pairwise" - Use LambdaMART to perform pairwise ranking where the pairwise loss is minimized
"rank:ndcg" - Use LambdaMART to perform list-wise ranking where Normalized Discounted Cumulative Gain (NDCG) is maximized
booster: The booster to use. Can be `gbtree`, `gblinear` or `dart`; `gbtree` and `dart` use tree based models while `gblinear` uses linear functions.
learning_rate: Step size shrinkage used in update to prevents overfitting. Range: [0,1].
min_split_loss: Minimum loss reduction required to make a further partition on a leaf node of the tree.
The larger `min_split_loss` is, the more conservative the algorithm will be. Range: [0,Inf].
max_depth: Maximum depth of a tree. Increasing this value will make the model more complex and more likely to overfit.
0 indicates no limit on depth. Range: [0,Inf].
Annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
"""
import pandas
import xgboost
df = pandas.read_csv(
training_data_path,
).convert_dtypes()
print("Training data information:")
df.info(verbose=True)
# Converting column types that XGBoost does not support
for column_name, dtype in df.dtypes.items():
if dtype in ["string", "object"]:
print(f"Treating the {dtype.name} column '{column_name}' as categorical.")
df[column_name] = df[column_name].astype("category")
print(f"Inferred {len(df[column_name].cat.categories)} categories for the '{column_name}' column.")
# Working around the XGBoost issue with nullable floats: https://github.com/dmlc/xgboost/issues/8213
if pandas.api.types.is_float_dtype(dtype):
# Converting from "Float64" to "float64"
df[column_name] = df[column_name].astype(dtype.name.lower())
print()
print("Final training data information:")
df.info(verbose=True)
training_data = xgboost.DMatrix(
data=df.drop(columns=[label_column_name]),
label=df[[label_column_name]],
enable_categorical=True,
)
booster_params = booster_params or {}
booster_params.setdefault("objective", objective)
booster_params.setdefault("booster", booster)
booster_params.setdefault("learning_rate", learning_rate)
booster_params.setdefault("min_split_loss", min_split_loss)
booster_params.setdefault("max_depth", max_depth)
starting_model = None
if starting_model_path:
starting_model = xgboost.Booster(model_file=starting_model_path)
print()
print("Training the model:")
model = xgboost.train(
params=booster_params,
dtrain=training_data,
num_boost_round=num_iterations,
xgb_model=starting_model,
evals=[(training_data, "training_data")],
)
# Saving the model in binary format
model.save_model(model_path)
model_config_str = model.save_config()
with open(model_config_path, "w") as model_config_file:
model_config_file.write(model_config_str)
import json
import argparse
_parser = argparse.ArgumentParser(prog='Train XGBoost model on CSV', description='Trains an XGBoost model.')
_parser.add_argument("--training-data", dest="training_data_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--label-column-name", dest="label_column_name", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--starting-model", dest="starting_model_path", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--num-iterations", dest="num_iterations", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--objective", dest="objective", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--booster", dest="booster", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--learning-rate", dest="learning_rate", type=float, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--min-split-loss", dest="min_split_loss", type=float, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--max-depth", dest="max_depth", type=int, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--booster-params", dest="booster_params", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--model", dest="model_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--model-config", dest="model_config_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = train_XGBoost_model_on_CSV(**_parsed_args)
args:
- --training-data
- {inputPath: training_data}
- --label-column-name
- {inputValue: label_column_name}
- if:
cond: {isPresent: starting_model}
then:
- --starting-model
- {inputPath: starting_model}
- if:
cond: {isPresent: num_iterations}
then:
- --num-iterations
- {inputValue: num_iterations}
- if:
cond: {isPresent: objective}
then:
- --objective
- {inputValue: objective}
- if:
cond: {isPresent: booster}
then:
- --booster
- {inputValue: booster}
- if:
cond: {isPresent: learning_rate}
then:
- --learning-rate
- {inputValue: learning_rate}
- if:
cond: {isPresent: min_split_loss}
then:
- --min-split-loss
- {inputValue: min_split_loss}
- if:
cond: {isPresent: max_depth}
then:
- --max-depth
- {inputValue: max_depth}
- if:
cond: {isPresent: booster_params}
then:
- --booster-params
- {inputValue: booster_params}
- --model
- {outputPath: model}
- --model-config
- {outputPath: model_config}
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/79d79efc5619692b28bcf14d37718077330ad617/components/XGBoost/Predict/component.yaml
digest: 86c68f66374a6cb0d0952fdd546fac65f750c9d1ed2578d9cb9094541bda9786
text: |
name: Xgboost predict on CSV
description: Makes predictions using a trained XGBoost model.
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/XGBoost/Predict/component.yaml'}
inputs:
- {name: data, type: CSV, description: Feature data in Apache Parquet format.}
- {name: model, type: XGBoostModel, description: Trained model in binary XGBoost format.}
- {name: label_column_name, type: String, description: Optional. Name of the column
containing the label data that is excluded during the prediction., optional: true}
- {name: prediction_column_name, type: String, default: prediction, optional: true}
outputs:
- {name: predictions, type: CSV, description: Model predictions.}
implementation:
container:
image: python:3.10
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'xgboost==1.6.1' 'pandas==1.4.3' 'numpy<2' || PIP_DISABLE_PIP_VERSION_CHECK=1
python3 -m pip install --quiet --no-warn-script-location 'xgboost==1.6.1' 'pandas==1.4.3'
'numpy<2' --user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def xgboost_predict_on_CSV(
data_path,
model_path,
predictions_path,
label_column_name = None,
prediction_column_name = "prediction",
):
"""Makes predictions using a trained XGBoost model.
Args:
data_path: Feature data in Apache Parquet format.
model_path: Trained model in binary XGBoost format.
predictions_path: Model predictions.
label_column_name: Optional. Name of the column containing the label data that is excluded during the prediction.
Annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
"""
from pathlib import Path
import numpy
import pandas
import xgboost
df = pandas.read_csv(
data_path,
).convert_dtypes()
print("Evaluation data information:")
df.info(verbose=True)
# Converting column types that XGBoost does not support
for column_name, dtype in df.dtypes.items():
if dtype in ["string", "object"]:
print(f"Treating the {dtype.name} column '{column_name}' as categorical.")
df[column_name] = df[column_name].astype("category")
print(f"Inferred {len(df[column_name].cat.categories)} categories for the '{column_name}' column.")
# Working around the XGBoost issue with nullable floats: https://github.com/dmlc/xgboost/issues/8213
if pandas.api.types.is_float_dtype(dtype):
# Converting from "Float64" to "float64"
df[column_name] = df[column_name].astype(dtype.name.lower())
print("Final evaluation data information:")
df.info(verbose=True)
if label_column_name is not None:
features_df = df.drop(columns=[label_column_name])
else:
features_df = df
testing_data = xgboost.DMatrix(
data=features_df,
enable_categorical=True,
)
model = xgboost.Booster(model_file=model_path)
predictions = model.predict(testing_data)
df[prediction_column_name] = predictions
Path(predictions_path).parent.mkdir(parents=True, exist_ok=True)
df.to_csv(predictions_path, index=False)
import argparse
_parser = argparse.ArgumentParser(prog='Xgboost predict on CSV', description='Makes predictions using a trained XGBoost model.')
_parser.add_argument("--data", dest="data_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--model", dest="model_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--label-column-name", dest="label_column_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--prediction-column-name", dest="prediction_column_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--predictions", dest="predictions_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = xgboost_predict_on_CSV(**_parsed_args)
args:
- --data
- {inputPath: data}
- --model
- {inputPath: model}
- if:
cond: {isPresent: label_column_name}
then:
- --label-column-name
- {inputValue: label_column_name}
- if:
cond: {isPresent: prediction_column_name}
then:
- --prediction-column-name
- {inputValue: prediction_column_name}
- --predictions
- {outputPath: predictions}
- name: Basics
components:
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/c36d9a4893c3caae0d166d9e783af28fcd3cdfe4/components/basics/Format_date_time/component.yaml
digest: 7784069b3bd1301674cfb4bbf7170b7db91ffd289138eb2d8838e3368158b70c
text: |
name: Format date and time
inputs:
- {name: Date, type: DateTime}
- {name: Format, type: String, default: "%Y-%m-%d %H:%M:%S.%N", description: "Format string for date and time. See [man date](https://linux.die.net/man/1/date)."}
outputs:
- {name: Formatted date, type: String}
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/basics/Format_date_time/component.yaml'
implementation:
container:
image: ubuntu
command:
- sh
- -exc
- |
date="$0"
format="$1"
output_path="$2"
mkdir -p "$(dirname "$output_path")"
date -d "$date" +"$format" >"$output_path"
- {inputValue: Date}
- {inputValue: Format}
- {outputPath: Formatted date}
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/37d98d43ad3193cf3516c134899f272d9643117c/components/basics/Calculate_hash/component.yaml
digest: 6afc1b9d9c845fcdf0e9820aa97c9544c0f8b1ec2b7c1cf481975231711f6503
text: |
name: Calculate data hash
inputs:
- {name: Data}
- {name: Hash algorithm, type: String, default: SHA256, description: "Hash algorithm to use. Supported values are MD5, SHA1, SHA256, SHA512, SHA3"}
outputs:
- {name: Hash}
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/basics/Calculate_hash/component.yaml'
implementation:
container:
image: alpine
command:
- sh
- -exc
- |
data_path="$0"
hash_algorithm="$1"
hash_path="$2"
mkdir -p "$(dirname "$hash_path")"
hash_algorithm=$(echo "$hash_algorithm" | tr '[:upper:]' '[:lower:]')
case "$hash_algorithm" in
md5|sha1|sha256|sha512|sha3) hash_program="${hash_algorithm}sum";;
*) echo "Unsupported hash algorithm $hash_algorithm"; exit 1;;
esac
if [ -d "$data_path" ]; then
# Calculating hash for directory
cd "$data_path"
find . -type f -print0 |
sort -z |
xargs -0 "$hash_program" |
"$hash_program" |
cut -d ' ' -f 1 > "$hash_path"
else
# Calculating hash for file
"$hash_program" "$data_path" |
cut -d ' ' -f 1 > "$hash_path"
fi
- {inputPath: Data}
- {inputValue: Hash algorithm}
- {outputPath: Hash}
folders:
- name: File system
components:
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/605cefc151797369752b51530a91cc02e7f913f8/components/filesystem/create_directory/component.yaml
digest: 6fa449465ecf656c02d07622acb5df045c3863acc15c607e1817f4e9f8078134
text: |
name: Create directory from files (5)
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: "https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/filesystem/create_directory/component.yaml"
inputs:
- { name: File 1 }
- { name: File 1 name, type: String, default: "1" }
- { name: File 2, optional: true }
- { name: File 2 name, type: String, default: "2" }
- { name: File 3, optional: true }
- { name: File 3 name, type: String, default: "3" }
- { name: File 4, optional: true }
- { name: File 4 name, type: String, default: "4" }
- { name: File 5, optional: true }
- { name: File 5 name, type: String, default: "5" }
outputs:
- { name: Directory, type: Directory }
implementation:
container:
image: alpine
command:
- sh
- -ec
- |
output_path="$1"
shift
mkdir -p "$output_path"
while [ "$#" -gt 0 ]; do
input_path="$1"
file_name="$2"
shift 2
cp -r "$input_path" "$output_path/$file_name"
done
- -c # stabilize $0 vs $1
- { outputPath: Directory }
- { inputPath: File 1 }
- { inputValue: File 1 name }
- if:
cond: { isPresent: File 2 }
then:
- { inputPath: File 2 }
- { inputValue: File 2 name }
- if:
cond: { isPresent: File 3 }
then:
- { inputPath: File 3 }
- { inputValue: File 3 name }
- if:
cond: { isPresent: File 4 }
then:
- { inputPath: File 4 }
- { inputValue: File 4 name }
- if:
cond: { isPresent: File 5 }
then:
- { inputPath: File 5 }
- { inputValue: File 5 name }
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/d8c4cf5e6403bc65bcf8d606e6baf87e2528a3dc/components/filesystem/get_file/component.yaml
digest: 4415166532fa69baa33378631802fab630f51ea1677ce6408cef946672f4a9d2
text: |
name: Get file
description: Get file from directory.
inputs:
- {name: Directory, type: Directory}
- {name: Subpath, type: String}
outputs:
- {name: File}
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/filesystem/get_file/component.yaml'
implementation:
container:
image: alpine
command:
- sh
- -ex
- -c
- |
mkdir -p "$(dirname "$2")"
cp -r "$0/$1" "$2"
- inputPath: Directory
- inputValue: Subpath
- outputPath: File
- name: Datasets
components:
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/57f780b15922061e59833541b71f3d099e710177/components/datasets/Chicago_Taxi_Trips/quick_start_version/component.yaml
digest: 42030acab16b71bbc3ad018563b5aedb94d373e72f7cb2b322bc27dbbee75e1b
text: |
name: Chicago Taxi Trips dataset
description: |
City of Chicago Taxi Trips dataset: https://data.cityofchicago.org/Transportation/Taxi-Trips/wrvz-psew
The input parameters configure the SQL query to the database.
The dataset is pretty big, so limit the number of results using the `Limit` or `Where` parameters.
Read [Socrata dev](https://dev.socrata.com/docs/queries/) for the advanced query syntax
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/datasets/Chicago_Taxi_Trips/quick_start_version/component.yaml'
inputs:
- {name: Where, type: String, default: 'trip_start_timestamp>="1900-01-01" AND trip_start_timestamp<"2100-01-01"'}
- {name: Limit, type: Integer, default: '1000', description: 'Number of rows to return. The rows are randomly sampled.'}
- {name: Select, type: String, default: 'tips,trip_seconds,trip_miles,pickup_community_area,dropoff_community_area,fare,tolls,extras,trip_total'}
- {name: Format, type: String, default: 'csv', description: 'Output data format. Supports csv,tsv,cml,rdf,json'}
outputs:
- {name: Table, description: 'Result type depends on format. CSV and TSV have header.'}
implementation:
container:
# image: curlimages/curl # Sets a non-root user which cannot write to mounted volumes. See https://github.com/curl/curl-docker/issues/22
image: alpine/curl:8.14.1
command:
- sh
- -c
- |
set -e -x -o pipefail
output_path="$0"
select="$1"
where="$2"
limit="$3"
format="$4"
mkdir -p "$(dirname "$output_path")"
curl --get 'https://data.cityofchicago.org/resource/wrvz-psew.'"${format}" \
--data-urlencode '$limit='"${limit}" \
--data-urlencode '$where='"${where}" \
--data-urlencode '$select='"${select}" \
| sed -E 's/"([^",\]*)"/\1/g' > "$output_path" # Removing unneeded quotes around all numbers
- {outputPath: Table}
- {inputValue: Select}
- {inputValue: Where}
- {inputValue: Limit}
- {inputValue: Format}
- name: Data manipulation
folders:
- name: Parquet
components:
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/96a177dd71d54c98573c4101d9a05ac801f1fa54/components/pandas/Select_columns/in_ApacheParquet_format/component.yaml
digest: 7cf49b426385086fbb58b2d7c900637439f9dfff0df5661591cb6840b125d57e
text: |
name: Select columns using Pandas on ApacheParquet data
description: Selects columns from a data table.
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/pandas/Select_columns/in_ApacheParquet_format/component.yaml'}
inputs:
- {name: table, type: ApacheParquet, description: Input data table.}
- {name: column_names, type: JsonArray, description: Names of the columns to select
from the table.}
outputs:
- {name: transformed_table, type: ApacheParquet, description: Transformed data table
that only has the chosen columns.}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'pandas==1.4.1' 'pyarrow==9.0.0' 'numpy<2' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'pandas==1.4.1' 'pyarrow==9.0.0' 'numpy<2'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def select_columns_using_Pandas_on_ApacheParquet_data(
table_path,
transformed_table_path,
column_names,
):
"""Selects columns from a data table.
Args:
table_path: Input data table.
transformed_table_path: Transformed data table that only has the chosen columns.
column_names: Names of the columns to select from the table.
"""
import pandas
df = pandas.read_parquet(table_path)
df = df[column_names]
df.to_parquet(transformed_table_path, index=False)
import json
import argparse
_parser = argparse.ArgumentParser(prog='Select columns using Pandas on ApacheParquet data', description='Selects columns from a data table.')
_parser.add_argument("--table", dest="table_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--column-names", dest="column_names", type=json.loads, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--transformed-table", dest="transformed_table_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = select_columns_using_Pandas_on_ApacheParquet_data(**_parsed_args)
args:
- --table
- {inputPath: table}
- --column-names
- {inputValue: column_names}
- --transformed-table
- {outputPath: transformed_table}
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/96a177dd71d54c98573c4101d9a05ac801f1fa54/components/pandas/Fill_all_missing_values/in_ApacheParquet_format/component.yaml
digest: 0fd11307bd634351c521d4ae5d32f547e0a77304b17e2eab046e092debb3b2b4
text: |
name: Fill all missing values using Pandas on ApacheParquet data
description: Fills the missing column items with the specified replacement value.
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/pandas/Fill_all_missing_values/in_ApacheParquet_format/component.yaml'}
inputs:
- {name: table, type: ApacheParquet, description: Input data table.}
- {name: replacement_value, type: String, description: The value to use when replacing
the missing items., default: '0', optional: true}
- {name: column_names, type: JsonArray, description: Names of the columns where to
perform the replacement., optional: true}
outputs:
- {name: transformed_table, type: ApacheParquet, description: Transformed data table
where missing values are filed.}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'pandas==1.4.1' 'pyarrow==9.0.0' 'numpy<2' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'pandas==1.4.1' 'pyarrow==9.0.0' 'numpy<2'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def fill_all_missing_values_using_Pandas_on_ApacheParquet_data(
table_path,
transformed_table_path,
replacement_value = "0",
column_names = None,
):
"""Fills the missing column items with the specified replacement value.
Args:
table_path: Input data table.
transformed_table_path: Transformed data table where missing values are filed.
replacement_value: The value to use when replacing the missing items.
column_names: Names of the columns where to perform the replacement.
"""
import pandas
df = pandas.read_parquet(path=table_path)
for column_name in column_names or df.columns:
column = df[column_name]
# The `.astype` method does not work correctly on booleans
# So we need to special-case them
if pandas.api.types.is_bool_dtype(column.dtype):
if replacement_value.lower() in ("true", "1"):
converted_replacement_value = True
elif replacement_value.lower() in ("false", "0"):
converted_replacement_value = False
else:
raise ValueError(
f"Cannot convert value '{replacement_value}' to boolean for column {column_name}."
)
else:
# Using Pandas to convert the replacement_value to column.dtype.
converted_replacement_value = pandas.Series(
replacement_value, dtype=column.dtype
).tolist()[0]
print(
f"Filling missing values in column '{column_name}' with '{converted_replacement_value}'"
)
column.fillna(value=converted_replacement_value)
df.to_parquet(
path=transformed_table_path,
index=False,
)
import json
import argparse
_parser = argparse.ArgumentParser(prog='Fill all missing values using Pandas on ApacheParquet data', description='Fills the missing column items with the specified replacement value.')
_parser.add_argument("--table", dest="table_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--replacement-value", dest="replacement_value", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--column-names", dest="column_names", type=json.loads, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--transformed-table", dest="transformed_table_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = fill_all_missing_values_using_Pandas_on_ApacheParquet_data(**_parsed_args)
args:
- --table
- {inputPath: table}
- if:
cond: {isPresent: replacement_value}
then:
- --replacement-value
- {inputValue: replacement_value}
- if:
cond: {isPresent: column_names}
then:
- --column-names
- {inputValue: column_names}
- --transformed-table
- {outputPath: transformed_table}
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/96a177dd71d54c98573c4101d9a05ac801f1fa54/components/pandas/Binarize_column/in_ApacheParquet_format/component.yaml
digest: 3a8d435090075b9064e62974a07baf316063b248b4c175d9e1f42bdf1bdd3439
text: |
name: Binarize column using Pandas on ApacheParquet data
description: Transforms a table column into a binary class column using a predicate.
metadata:
annotations: {author: Alexey Volkov <alexey.volkov@ark-kun.com>, canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/pandas/Binarize_column/in_ApacheParquet_format/component.yaml'}
inputs:
- {name: table, type: ApacheParquet, description: Input data table.}
- {name: column_name, type: String, description: Name of the column to transform to
binary class.}
- {name: predicate, type: String, description: Expression that determines whether
the column value is mapped to class 0 (false) or class 1 (true)., default: '>
0', optional: true}
- {name: new_column_name, type: String, description: Name for the new class column.
Equals column_name by default., optional: true}
- name: keep_original_column
type: Boolean
description: Whether to keep the original column (column_name) in the table.
default: "False"
optional: true
outputs:
- {name: transformed_table, type: ApacheParquet, description: Transformed data table
with the binary class column.}
implementation:
container:
image: python:3.9
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'pandas==1.4.3' 'pyarrow==9.0.0' 'numpy<2' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'pandas==1.4.3' 'pyarrow==9.0.0' 'numpy<2'
--user) && "$0" "$@"
- sh
- -ec
- |
program_path=$(mktemp)
printf "%s" "$0" > "$program_path"
python3 -u "$program_path" "$@"
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os
os.makedirs(os.path.dirname(file_path), exist_ok=True)
return file_path
def binarize_column_using_Pandas_on_ApacheParquet_data(
table_path,
transformed_table_path,
column_name,
predicate = "> 0",
new_column_name = None,
keep_original_column = False,
):
"""Transforms a table column into a binary class column using a predicate.
Args:
table_path: Input data table.
transformed_table_path: Transformed data table with the binary class column.
column_name: Name of the column to transform to binary class.
predicate: Expression that determines whether the column value is mapped to class 0 (false) or class 1 (true).
new_column_name: Name for the new class column. Equals column_name by default.
keep_original_column: Whether to keep the original column (column_name) in the table.
"""
import pandas
df = pandas.read_parquet(path=table_path)
original_series = df[column_name]
# Dynamically executing the predicate code
# Variable namespace for code execution
namespace = dict(x=original_series)
# I though that there should be no space before `predicate` so that "dot" predicate methods like ".between(min, max)" work.
# However Python allows spaces before dot: `df .isna()`.
# So having a space is not a problem
transform_code = f"""new_series_boolean = x {predicate}"""
# Note: exec() takes no keyword arguments
# exec(__source=transform_code, __globals=namespace)
exec(transform_code, namespace)
new_series_boolean = namespace["new_series_boolean"]
# There are multiple ways to convert boolean column to integer.
# .apply(int) might be faster. https://stackoverflow.com/a/49804868/1497385
# TODO: Do a proper benchmark.
new_series = new_series_boolean.apply(int)
# new_series = new_series_boolean.astype(int)
# new_series = new_series_boolean.replace({False: 0, True: 1})
if new_column_name:
df.insert(loc=0, column=new_column_name, value=new_series)
if not keep_original_column:
df = df.drop(columns=[column_name])
else:
df[column_name] = new_series
df.to_parquet(path=transformed_table_path)
def _deserialize_bool(s) -> bool:
from distutils.util import strtobool
return strtobool(s) == 1
import argparse
_parser = argparse.ArgumentParser(prog='Binarize column using Pandas on ApacheParquet data', description='Transforms a table column into a binary class column using a predicate.')
_parser.add_argument("--table", dest="table_path", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--column-name", dest="column_name", type=str, required=True, default=argparse.SUPPRESS)
_parser.add_argument("--predicate", dest="predicate", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--new-column-name", dest="new_column_name", type=str, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--keep-original-column", dest="keep_original_column", type=_deserialize_bool, required=False, default=argparse.SUPPRESS)
_parser.add_argument("--transformed-table", dest="transformed_table_path", type=_make_parent_dirs_and_return_path, required=True, default=argparse.SUPPRESS)
_parsed_args = vars(_parser.parse_args())
_outputs = binarize_column_using_Pandas_on_ApacheParquet_data(**_parsed_args)
args:
- --table
- {inputPath: table}
- --column-name
- {inputValue: column_name}
- if:
cond: {isPresent: predicate}
then:
- --predicate
- {inputValue: predicate}
- if:
cond: {isPresent: new_column_name}
then:
- --new-column-name
- {inputValue: new_column_name}
- if:
cond: {isPresent: keep_original_column}
then:
- --keep-original-column
- {inputValue: keep_original_column}
- --transformed-table
- {outputPath: transformed_table}
- url: https://raw.githubusercontent.com/Ark-kun/pipeline_components/96a177dd71d54c98573c4101d9a05ac801f1fa54/components/pandas/Transform_DataFrame/in_ApacheParquet_format/component.yaml
digest: 45cad5c51cbebcc10c6c552709ba367e3f516f98a33dfaadd776737d69375885
text: |
name: Pandas Transform DataFrame in ApacheParquet format
description: |-
Transform DataFrame loaded from an ApacheParquet file.
Inputs:
table: DataFrame to transform.
transform_code: Transformation code. Code is written in Python and can consist of multiple lines.
The DataFrame variable is called "df".
Examples:
- `df['prod'] = df['X'] * df['Y']`
- `df = df[['X', 'prod']]`
- `df.insert(0, "is_positive", df["X"] > 0)`
Outputs:
transformed_table: Transformed DataFrame.
Annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
inputs:
- {name: table, type: ApacheParquet}
- {name: transform_code, type: PythonCode}
outputs:
- {name: transformed_table, type: ApacheParquet}
metadata:
annotations:
author: Alexey Volkov <alexey.volkov@ark-kun.com>
canonical_location: 'https://raw.githubusercontent.com/Ark-kun/pipeline_components/master/components/pandas/Transform_DataFrame/in_ApacheParquet_format/component.yaml'
implementation:
container:
image: python:3.7
command:
- sh
- -c
- (PIP_DISABLE_PIP_VERSION_CHECK=1 python3 -m pip install --quiet --no-warn-script-location
'pandas==1.0.4' 'pyarrow==0.14.1' 'numpy<2' || PIP_DISABLE_PIP_VERSION_CHECK=1 python3
-m pip install --quiet --no-warn-script-location 'pandas==1.0.4' 'pyarrow==0.14.1' 'numpy<2'
--user) && "$0" "$@"
- python3
- -u
- -c
- |
def _make_parent_dirs_and_return_path(file_path: str):
import os