Campfireman commited on
Commit
69a2a60
1 Parent(s): b67b7da

Create functions.py

Browse files
Files changed (1) hide show
  1. functions.py +147 -0
functions.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import requests
3
+ import os
4
+ import joblib
5
+ import pandas as pd
6
+
7
+ import json
8
+
9
+
10
+ def decode_features(df, feature_view):
11
+ """Decodes features in the input DataFrame using corresponding Hopsworks Feature Store transformation functions"""
12
+ df_res = df.copy()
13
+
14
+ import inspect
15
+
16
+
17
+ td_transformation_functions = feature_view._batch_scoring_server._transformation_functions
18
+
19
+ res = {}
20
+ for feature_name in td_transformation_functions:
21
+ if feature_name in df_res.columns:
22
+ td_transformation_function = td_transformation_functions[feature_name]
23
+ sig, foobar_locals = inspect.signature(td_transformation_function.transformation_fn), locals()
24
+ param_dict = dict([(param.name, param.default) for param in sig.parameters.values() if param.default != inspect._empty])
25
+ if td_transformation_function.name == "min_max_scaler":
26
+ df_res[feature_name] = df_res[feature_name].map(
27
+ lambda x: x * (param_dict["max_value"] - param_dict["min_value"]) + param_dict["min_value"])
28
+
29
+ elif td_transformation_function.name == "standard_scaler":
30
+ df_res[feature_name] = df_res[feature_name].map(
31
+ lambda x: x * param_dict['std_dev'] + param_dict["mean"])
32
+ elif td_transformation_function.name == "label_encoder":
33
+ dictionary = param_dict['value_to_index']
34
+ dictionary_ = {v: k for k, v in dictionary.items()}
35
+ df_res[feature_name] = df_res[feature_name].map(
36
+ lambda x: dictionary_[x])
37
+ return df_res
38
+
39
+
40
+ def get_model(project, model_name, evaluation_metric, sort_metrics_by):
41
+ """Retrieve desired model or download it from the Hopsworks Model Registry.
42
+ In second case, it will be physically downloaded to this directory"""
43
+ TARGET_FILE = "model_temp.pkl"
44
+ list_of_files = [os.path.join(dirpath,filename) for dirpath, _, filenames \
45
+ in os.walk('.') for filename in filenames if filename == TARGET_FILE]
46
+
47
+ if list_of_files:
48
+ model_path = list_of_files[0]
49
+ model = joblib.load(model_path)
50
+ else:
51
+ if not os.path.exists(TARGET_FILE):
52
+ mr = project.get_model_registry()
53
+ # get best model based on custom metrics
54
+ model = mr.get_best_model(model_name,
55
+ evaluation_metric,
56
+ sort_metrics_by)
57
+ model_dir = model.download()
58
+ model = joblib.load(model_dir + "/model_temp.pkl")
59
+
60
+ return model
61
+
62
+
63
+
64
+ def get_weather_json(date, WEATHER_API_KEY):
65
+ return requests.get(f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/helsinki/{date}?unitGroup=metric&include=days&key={WEATHER_API_KEY}&contentType=json').json()
66
+
67
+
68
+ def get_weather_data(date):
69
+ WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')
70
+ json = get_weather_json(date, WEATHER_API_KEY)
71
+ data = json['days'][0]
72
+
73
+ return [
74
+ json['address'].capitalize(),
75
+ data['datetime'],
76
+ data['tempmax'],
77
+ data['tempmin'],
78
+ data['temp'],
79
+ data['feelslikemax'],
80
+ data['feelslikemin'],
81
+ data['feelslike'],
82
+ data['dew'],
83
+ data['humidity'],
84
+ data['precip'],
85
+ data['precipprob'],
86
+ data['precipcover'],
87
+ data['snow'],
88
+ data['snowdepth'],
89
+ data['windgust'],
90
+ data['windspeed'],
91
+ data['winddir'],
92
+ data['pressure'],
93
+ data['cloudcover'],
94
+ data['visibility'],
95
+ data['solarradiation'],
96
+ data['solarenergy'],
97
+ data['uvindex'],
98
+ data['conditions']
99
+ ]
100
+
101
+
102
+ def get_weather_df(data):
103
+ col_names = [
104
+ 'city',
105
+ 'date',
106
+ 'tempmax',
107
+ 'tempmin',
108
+ 'temp',
109
+ 'feelslikemax',
110
+ 'feelslikemin',
111
+ 'feelslike',
112
+ 'dew',
113
+ 'humidity',
114
+ 'precip',
115
+ 'precipprob',
116
+ 'precipcover',
117
+ 'snow',
118
+ 'snowdepth',
119
+ 'windgust',
120
+ 'windspeed',
121
+ 'winddir',
122
+ 'pressure',
123
+ 'cloudcover',
124
+ 'visibility',
125
+ 'solarradiation',
126
+ 'solarenergy',
127
+ 'uvindex',
128
+ 'conditions'
129
+ ]
130
+
131
+ new_data = pd.DataFrame(
132
+ data,
133
+ columns=col_names
134
+ )
135
+ new_data.date = new_data.date.apply(timestamp_2_time1)
136
+
137
+ return new_data
138
+
139
+ def timestamp_2_time1(x):
140
+ dt_obj = datetime.strptime(str(x), '%Y-%m-%d')
141
+ dt_obj = dt_obj.timestamp() * 1000
142
+ return int(dt_obj)
143
+
144
+ def timestamp_2_time(x):
145
+ dt_obj = datetime.strptime(str(x), '%m/%d/%Y')
146
+ dt_obj = dt_obj.timestamp() * 1000
147
+ return int(dt_obj)