Orangefish commited on
Commit
84a1a7d
1 Parent(s): 760d8b7

Create functions.py

Browse files
Files changed (1) hide show
  1. functions.py +244 -0
functions.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.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.pkl")
59
+
60
+ return model
61
+
62
+
63
+ def get_air_json(AIR_QUALITY_API_KEY):
64
+ return requests.get(f'https://api.waqi.info/feed/Helsinki/?token={AIR_QUALITY_API_KEY}').json()['data']
65
+
66
+
67
+
68
+ def get_air_quality_data1():
69
+
70
+ AIR_QUALITY_API_KEY = os.getenv('AIR_QUALITY_API_KEY')
71
+ json = get_air_json(AIR_QUALITY_API_KEY)
72
+
73
+ print(json)
74
+ # iaqi = json['iaqi']
75
+ # forecast = json['forecast']['daily']
76
+ return [
77
+ json['date'], # AQI
78
+ json['pm25'],
79
+ json['pm10'],
80
+ json['o3'],
81
+ json['no2'],
82
+
83
+ ]
84
+
85
+ def get_air_quality_data():
86
+ AIR_QUALITY_API_KEY = os.getenv('AIR_QUALITY_API_KEY')
87
+ json = get_air_json(AIR_QUALITY_API_KEY)
88
+ iaqi = json['iaqi']
89
+ forecast = json['forecast']['daily']
90
+ return [
91
+ json['aqi'], # AQI
92
+ json['time']['s'][:10], # Date
93
+ iaqi['h']['v'],
94
+ iaqi['p']['v'],
95
+ iaqi['pm10']['v'],
96
+ iaqi['t']['v'],
97
+ forecast['o3'][0]['avg'],
98
+ forecast['o3'][0]['max'],
99
+ forecast['o3'][0]['min'],
100
+ forecast['pm10'][0]['avg'],
101
+ forecast['pm10'][0]['max'],
102
+ forecast['pm10'][0]['min'],
103
+ forecast['pm25'][0]['avg'],
104
+ forecast['pm25'][0]['max'],
105
+ forecast['pm25'][0]['min'],
106
+ forecast['uvi'][0]['avg'],
107
+ forecast['uvi'][0]['avg'],
108
+ forecast['uvi'][0]['avg']
109
+ ]
110
+
111
+ def get_air_quality_df1(data):
112
+ col_names = [
113
+ 'aqi',
114
+ 'date',
115
+ 'pm25',
116
+ 'pm10',
117
+ 'o3',
118
+ 'no2',
119
+
120
+ ]
121
+
122
+ new_data = pd.DataFrame(
123
+ data,
124
+ columns=col_names
125
+ )
126
+ new_data.date = new_data.date.apply(timestamp_2_time)
127
+
128
+ return new_data
129
+
130
+ def get_air_quality_df(data):
131
+ col_names = [
132
+ 'aqi',
133
+ 'date',
134
+ 'iaqi_h',
135
+ 'iaqi_p',
136
+ 'iaqi_pm10',
137
+ 'iaqi_t',
138
+ 'o3_avg',
139
+ 'o3_max',
140
+ 'o3_min',
141
+ 'pm10_avg',
142
+ 'pm10_max',
143
+ 'pm10_min',
144
+ 'pm25_avg',
145
+ 'pm25_max',
146
+ 'pm25_min',
147
+ 'uvi_avg',
148
+ 'uvi_max',
149
+ 'uvi_min',
150
+ ]
151
+
152
+ new_data = pd.DataFrame(
153
+ data,
154
+ columns=col_names
155
+ )
156
+ new_data.date = new_data.date.apply(timestamp_2_time1)
157
+
158
+ return new_data
159
+
160
+
161
+ def get_weather_json(date, WEATHER_API_KEY):
162
+ 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()
163
+
164
+
165
+ def get_weather_data(date):
166
+ WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')
167
+ json = get_weather_json(date, WEATHER_API_KEY)
168
+ data = json['days'][0]
169
+
170
+ return [
171
+ json['address'].capitalize(),
172
+ data['datetime'],
173
+ data['tempmax'],
174
+ data['tempmin'],
175
+ data['temp'],
176
+ data['feelslikemax'],
177
+ data['feelslikemin'],
178
+ data['feelslike'],
179
+ data['dew'],
180
+ data['humidity'],
181
+ data['precip'],
182
+ data['precipprob'],
183
+ data['precipcover'],
184
+ data['snow'],
185
+ data['snowdepth'],
186
+ data['windgust'],
187
+ data['windspeed'],
188
+ data['winddir'],
189
+ data['pressure'],
190
+ data['cloudcover'],
191
+ data['visibility'],
192
+ data['solarradiation'],
193
+ data['solarenergy'],
194
+ data['uvindex'],
195
+ data['conditions']
196
+ ]
197
+
198
+
199
+ def get_weather_df(data):
200
+ col_names = [
201
+ 'city',
202
+ 'date',
203
+ 'tempmax',
204
+ 'tempmin',
205
+ 'temp',
206
+ 'feelslikemax',
207
+ 'feelslikemin',
208
+ 'feelslike',
209
+ 'dew',
210
+ 'humidity',
211
+ 'precip',
212
+ 'precipprob',
213
+ 'precipcover',
214
+ 'snow',
215
+ 'snowdepth',
216
+ 'windgust',
217
+ 'windspeed',
218
+ 'winddir',
219
+ 'pressure',
220
+ 'cloudcover',
221
+ 'visibility',
222
+ 'solarradiation',
223
+ 'solarenergy',
224
+ 'uvindex',
225
+ 'conditions'
226
+ ]
227
+
228
+ new_data = pd.DataFrame(
229
+ data,
230
+ columns=col_names
231
+ )
232
+ new_data.date = new_data.date.apply(timestamp_2_time1)
233
+
234
+ return new_data
235
+
236
+ def timestamp_2_time1(x):
237
+ dt_obj = datetime.strptime(str(x), '%Y-%m-%d')
238
+ dt_obj = dt_obj.timestamp() * 1000
239
+ return int(dt_obj)
240
+
241
+ def timestamp_2_time(x):
242
+ dt_obj = datetime.strptime(str(x), '%m/%d/%Y')
243
+ dt_obj = dt_obj.timestamp() * 1000
244
+ return int(dt_obj)