SebLih commited on
Commit
6bc6fd8
·
1 Parent(s): a0a1991

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
+ 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(
24
+ td_transformation_function.transformation_fn), locals()
25
+ param_dict = dict([(param.name, param.default) for param in sig.parameters.values(
26
+ ) if param.default != inspect._empty])
27
+ if td_transformation_function.name == "min_max_scaler":
28
+ df_res[feature_name] = df_res[feature_name].map(
29
+ lambda x: x * (param_dict["max_value"] - param_dict["min_value"]) + param_dict["min_value"])
30
+
31
+ elif td_transformation_function.name == "standard_scaler":
32
+ df_res[feature_name] = df_res[feature_name].map(
33
+ lambda x: x * param_dict['std_dev'] + param_dict["mean"])
34
+ elif td_transformation_function.name == "label_encoder":
35
+ dictionary = param_dict['value_to_index']
36
+ dictionary_ = {v: k for k, v in dictionary.items()}
37
+ df_res[feature_name] = df_res[feature_name].map(
38
+ lambda x: dictionary_[x])
39
+ return df_res
40
+
41
+
42
+ def get_model(project, model_name, evaluation_metric, sort_metrics_by):
43
+ """Retrieve desired model or download it from the Hopsworks Model Registry.
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
+ return [
75
+ city_name,
76
+ json['aqi'], # AQI
77
+ json['time']['s'][:10], # Date
78
+ iaqi['h']['v'],
79
+ iaqi['p']['v'],
80
+ iaqi['pm10']['v'],
81
+ iaqi['t']['v'],
82
+ forecast['o3'][0]['avg'],
83
+ forecast['o3'][0]['max'],
84
+ forecast['o3'][0]['min'],
85
+ forecast['pm10'][0]['avg'],
86
+ forecast['pm10'][0]['max'],
87
+ forecast['pm10'][0]['min'],
88
+ forecast['pm25'][0]['avg'],
89
+ forecast['pm25'][0]['max'],
90
+ forecast['pm25'][0]['min'],
91
+ forecast['uvi'][0]['avg'],
92
+ forecast['uvi'][0]['avg'],
93
+ forecast['uvi'][0]['avg']
94
+ ]
95
+
96
+
97
+ def get_air_quality_df(data):
98
+ col_names = [
99
+ 'city',
100
+ 'aqi',
101
+ 'date',
102
+ 'iaqi_h',
103
+ 'iaqi_p',
104
+ 'iaqi_pm10',
105
+ 'iaqi_t',
106
+ 'o3_avg',
107
+ 'o3_max',
108
+ 'o3_min',
109
+ 'pm10_avg',
110
+ 'pm10_max',
111
+ 'pm10_min',
112
+ 'pm25_avg',
113
+ 'pm25_max',
114
+ 'pm25_min',
115
+ 'uvi_avg',
116
+ 'uvi_max',
117
+ 'uvi_min',
118
+ ]
119
+
120
+ new_data = pd.DataFrame(
121
+ data,
122
+ columns=col_names
123
+ )
124
+ new_data.date = new_data.date.apply(timestamp_2_time_weather)
125
+
126
+ return new_data
127
+
128
+
129
+ def get_weather_json(city, date, WEATHER_API_KEY):
130
+ 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()
131
+
132
+
133
+ def get_weather_data(city_name, date):
134
+ WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')
135
+ json = get_weather_json(city_name, date, WEATHER_API_KEY)
136
+ data = json['days'][0]
137
+
138
+ return [
139
+ json['address'].capitalize(),
140
+ data['datetime'],
141
+ data['tempmax'],
142
+ data['tempmin'],
143
+ data['temp'],
144
+ data['feelslikemax'],
145
+ data['feelslikemin'],
146
+ data['feelslike'],
147
+ data['dew'],
148
+ data['humidity'],
149
+ data['precip'],
150
+ data['precipprob'],
151
+ data['precipcover'],
152
+ data['snow'],
153
+ data['snowdepth'],
154
+ data['windgust'],
155
+ data['windspeed'],
156
+ data['winddir'],
157
+ data['pressure'],
158
+ data['cloudcover'],
159
+ data['visibility'],
160
+ data['solarradiation'],
161
+ data['solarenergy'],
162
+ data['uvindex'],
163
+ data['conditions']
164
+ ]
165
+
166
+
167
+ def get_weather_df(data):
168
+ col_names = [
169
+ 'city',
170
+ 'date',
171
+ 'tempmax',
172
+ 'tempmin',
173
+ 'temp',
174
+ 'feelslikemax',
175
+ 'feelslikemin',
176
+ 'feelslike',
177
+ 'dew',
178
+ 'humidity',
179
+ 'precip',
180
+ 'precipprob',
181
+ 'precipcover',
182
+ 'snow',
183
+ 'snowdepth',
184
+ 'windgust',
185
+ 'windspeed',
186
+ 'winddir',
187
+ 'pressure',
188
+ 'cloudcover',
189
+ 'visibility',
190
+ 'solarradiation',
191
+ 'solarenergy',
192
+ 'uvindex',
193
+ 'conditions'
194
+ ]
195
+
196
+ new_data = pd.DataFrame(
197
+ data,
198
+ columns=col_names
199
+ )
200
+ new_data.date = new_data.date.apply(timestamp_2_time_weather)
201
+
202
+ return new_data
203
+
204
+
205
+ def timestamp_2_time(x):
206
+ dt_obj = datetime.strptime(str(x), '%Y/%m/%d')
207
+ dt_obj = dt_obj.timestamp() * 1000
208
+ return int(dt_obj)
209
+
210
+
211
+ def timestamp_2_time_weather(x):
212
+ dt_obj = datetime.strptime(str(x), '%Y-%m-%d')
213
+ dt_obj = dt_obj.timestamp() * 1000
214
+ return int(dt_obj)
215
+
216
+ def add_city_column(df, cityname):
217
+ df['city'] = cityname
218
+ return df
219
+
220
+
221
+ def add_aqi_column(df):
222
+ dfCopy = df.copy()
223
+
224
+ df['aqi'] = dfCopy[dfCopy.columns].max(axis=1)
225
+ return df
226
+
227
+ def remove_nans_in_csv(df):
228
+ df = df.dropna()
229
+ #df = df.fillna(0)
230
+ return df