Yasaman commited on
Commit
e819d97
·
1 Parent(s): fa4ff23

Upload functions.py

Browse files
Files changed (1) hide show
  1. functions.py +230 -0
functions.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import requests
3
+ import os
4
+ import joblib
5
+ import pandas as pd
6
+
7
+ from dotenv import load_dotenv
8
+ load_dotenv()
9
+
10
+
11
+ def decode_features(df, feature_view):
12
+ """Decodes features in the input DataFrame using corresponding Hopsworks Feature Store transformation functions"""
13
+ df_res = df.copy()
14
+
15
+ import inspect
16
+
17
+
18
+ td_transformation_functions = feature_view._batch_scoring_server._transformation_functions
19
+
20
+ res = {}
21
+ for feature_name in td_transformation_functions:
22
+ if feature_name in df_res.columns:
23
+ td_transformation_function = td_transformation_functions[feature_name]
24
+ sig, foobar_locals = inspect.signature(td_transformation_function.transformation_fn), locals()
25
+ param_dict = dict([(param.name, param.default) for param in sig.parameters.values() if param.default != inspect._empty])
26
+ if td_transformation_function.name == "min_max_scaler":
27
+ df_res[feature_name] = df_res[feature_name].map(
28
+ lambda x: x * (param_dict["max_value"] - param_dict["min_value"]) + param_dict["min_value"])
29
+
30
+ elif td_transformation_function.name == "standard_scaler":
31
+ df_res[feature_name] = df_res[feature_name].map(
32
+ lambda x: x * param_dict['std_dev'] + param_dict["mean"])
33
+ elif td_transformation_function.name == "label_encoder":
34
+ dictionary = param_dict['value_to_index']
35
+ dictionary_ = {v: k for k, v in dictionary.items()}
36
+ df_res[feature_name] = df_res[feature_name].map(
37
+ lambda x: dictionary_[x])
38
+ return df_res
39
+
40
+
41
+ def get_model(project, model_name, evaluation_metric, sort_metrics_by):
42
+ """Retrieve desired model or download it from the Hopsworks Model Registry.
43
+
44
+ In second case, it will be physically downloaded to this directory"""
45
+ TARGET_FILE = "model.pkl"
46
+ list_of_files = [os.path.join(dirpath,filename) for dirpath, _, filenames \
47
+ in os.walk('.') for filename in filenames if filename == TARGET_FILE]
48
+
49
+ if list_of_files:
50
+ model_path = list_of_files[0]
51
+ model = joblib.load(model_path)
52
+ else:
53
+ if not os.path.exists(TARGET_FILE):
54
+ mr = project.get_model_registry()
55
+ # get best model based on custom metrics
56
+ model = mr.get_best_model(model_name,
57
+ evaluation_metric,
58
+ sort_metrics_by)
59
+ model_dir = model.download()
60
+ model = joblib.load(model_dir + "/model.pkl")
61
+
62
+ return model
63
+
64
+
65
+ def get_air_json(city_name, AIR_QUALITY_API_KEY):
66
+ return requests.get(f'https://api.waqi.info/feed/{city_name}/?token={AIR_QUALITY_API_KEY}').json()['data']
67
+
68
+
69
+ def get_air_quality_data(city_name):
70
+ AIR_QUALITY_API_KEY = os.getenv('AIR_QUALITY_API_KEY')
71
+ json = get_air_json(city_name, AIR_QUALITY_API_KEY)
72
+ iaqi = json['iaqi']
73
+ forecast = json['forecast']['daily']
74
+ print(json)
75
+ if 'uvi' in forecast:
76
+ return [
77
+ city_name,
78
+ json['aqi'], # AQI
79
+ json['time']['s'][:10], # Date
80
+ iaqi['h']['v'],
81
+ iaqi['p']['v'],
82
+ iaqi['pm10']['v'],
83
+ iaqi['t']['v'],
84
+ forecast['o3'][2]['avg'],
85
+ forecast['o3'][2]['max'],
86
+ forecast['o3'][2]['min'],
87
+ forecast['pm10'][2]['avg'],
88
+ forecast['pm10'][2]['max'],
89
+ forecast['pm10'][2]['min'],
90
+ forecast['pm25'][2]['avg'],
91
+ forecast['pm25'][2]['max'],
92
+ forecast['pm25'][2]['min'],
93
+ forecast['uvi'][2]['avg'],
94
+ forecast['uvi'][2]['avg'],
95
+ forecast['uvi'][2]['avg']
96
+ ]
97
+ else:
98
+ return [
99
+ city_name,
100
+ json['aqi'], # AQI
101
+ json['time']['s'][:10], # Date
102
+ iaqi['h']['v'],
103
+ iaqi['p']['v'],
104
+ iaqi['pm10']['v'],
105
+ iaqi['t']['v'],
106
+ forecast['o3'][2]['avg'],
107
+ forecast['o3'][2]['max'],
108
+ forecast['o3'][2]['min'],
109
+ forecast['pm10'][2]['avg'],
110
+ forecast['pm10'][2]['max'],
111
+ forecast['pm10'][2]['min'],
112
+ forecast['pm25'][2]['avg'],
113
+ forecast['pm25'][2]['max'],
114
+ forecast['pm25'][2]['min'],
115
+ 0,
116
+ 0,
117
+ 0
118
+ ]
119
+
120
+ def get_air_quality_df(data):
121
+ col_names = [
122
+ 'city',
123
+ 'aqi',
124
+ 'date',
125
+ 'iaqi_h',
126
+ 'iaqi_p',
127
+ 'iaqi_pm10',
128
+ 'iaqi_t',
129
+ 'o3_avg',
130
+ 'o3_max',
131
+ 'o3_min',
132
+ 'pm10_avg',
133
+ 'pm10_max',
134
+ 'pm10_min',
135
+ 'pm25_avg',
136
+ 'pm25_max',
137
+ 'pm25_min',
138
+ 'uvi_avg',
139
+ 'uvi_max',
140
+ 'uvi_min',
141
+ ]
142
+
143
+ new_data = pd.DataFrame(
144
+ data,
145
+ columns=col_names
146
+ )
147
+ new_data.date = new_data.date.apply(timestamp_2_time)
148
+
149
+ return new_data
150
+
151
+
152
+ def get_weather_json(city, date, WEATHER_API_KEY):
153
+ return requests.get(f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/{city.lower()}/{date}?unitGroup=metric&include=days&key={WEATHER_API_KEY}&contentType=json').json()
154
+
155
+
156
+ def get_weather_data(city_name, date):
157
+ WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')
158
+ json = get_weather_json(city_name, date, WEATHER_API_KEY)
159
+ data = json['days'][0]
160
+
161
+ return [
162
+ json['address'].capitalize(),
163
+ data['datetime'],
164
+ data['tempmax'],
165
+ data['tempmin'],
166
+ data['temp'],
167
+ data['feelslikemax'],
168
+ data['feelslikemin'],
169
+ data['feelslike'],
170
+ data['dew'],
171
+ data['humidity'],
172
+ data['precip'],
173
+ data['precipprob'],
174
+ data['precipcover'],
175
+ data['snow'],
176
+ data['snowdepth'],
177
+ data['windgust'],
178
+ data['windspeed'],
179
+ data['winddir'],
180
+ data['pressure'],
181
+ data['cloudcover'],
182
+ data['visibility'],
183
+ data['solarradiation'],
184
+ data['solarenergy'],
185
+ data['uvindex'],
186
+ data['conditions']
187
+ ]
188
+
189
+
190
+ def get_weather_df(data):
191
+ col_names = [
192
+ 'city',
193
+ 'date',
194
+ 'tempmax',
195
+ 'tempmin',
196
+ 'temp',
197
+ 'feelslikemax',
198
+ 'feelslikemin',
199
+ 'feelslike',
200
+ 'dew',
201
+ 'humidity',
202
+ 'precip',
203
+ 'precipprob',
204
+ 'precipcover',
205
+ 'snow',
206
+ 'snowdepth',
207
+ 'windgust',
208
+ 'windspeed',
209
+ 'winddir',
210
+ 'pressure',
211
+ 'cloudcover',
212
+ 'visibility',
213
+ 'solarradiation',
214
+ 'solarenergy',
215
+ 'uvindex',
216
+ 'conditions'
217
+ ]
218
+
219
+ new_data = pd.DataFrame(
220
+ data,
221
+ columns=col_names
222
+ )
223
+ new_data.date = new_data.date.apply(timestamp_2_time)
224
+
225
+ return new_data
226
+
227
+ def timestamp_2_time(x):
228
+ dt_obj = datetime.strptime(str(x), '%Y-%m-%d')
229
+ dt_obj = dt_obj.timestamp() * 1000
230
+ return int(dt_obj)