wschyfx commited on
Commit
86bcb8f
·
1 Parent(s): 3fd066e

Create functions.py

Browse files
Files changed (1) hide show
  1. functions.py +209 -0
functions.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, version_name):
42
+ """Retrieve desired model or download it from the Hopsworks Model Registry.
43
+ In second case, it will be physically downloaded to this directory"""
44
+ TARGET_FILE = "model.pkl"
45
+ list_of_files = [os.path.join(dirpath,filename) for dirpath, _, filenames \
46
+ in os.walk('.') for filename in filenames if filename == TARGET_FILE]
47
+
48
+ if list_of_files:
49
+ model_path = list_of_files[0]
50
+ model = joblib.load(model_path)
51
+ else:
52
+ if not os.path.exists(TARGET_FILE):
53
+ mr = project.get_model_registry()
54
+ # get best model based on custom metrics
55
+ model = mr.get_best_model(model_name,
56
+ evaluation_metric,
57
+ sort_metrics_by,
58
+ version = version_name)
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(city_name)
75
+ print(forecast.keys())
76
+ return [
77
+ # city_name,
78
+ # json['aqi'], # AQI
79
+ json['time']['s'][:10], # Date
80
+ float(iaqi['pm25']['v']),
81
+ float(iaqi['pm10']['v']),
82
+ iaqi['no2']['v']
83
+ # iaqi['t']['v']
84
+ # forecast['o3'][0]['avg'],
85
+ # forecast['o3'][0]['max'],
86
+ # forecast['o3'][0]['min'],
87
+ # forecast['pm10'][0]['avg'],
88
+ # forecast['pm10'][0]['max'],
89
+ # forecast['pm10'][0]['min'],
90
+ # forecast['pm25'][0]['avg'],
91
+ # forecast['pm25'][0]['max'],
92
+ # forecast['pm25'][0]['min'],
93
+ # forecast['uvi'][0]['avg'],
94
+ # forecast['uvi'][0]['max'],
95
+ # forecast['uvi'][0]['min']
96
+ # forecast['pm25'][0]['min']
97
+ ]
98
+
99
+ def get_air_quality_df(data):
100
+ col_names = [
101
+ # 'city',
102
+ # 'aqi',
103
+ 'date',
104
+ 'pm25',
105
+ 'pm10',
106
+ 'no2'
107
+ # 'o3_avg',
108
+ # 'o3_max',
109
+ # 'o3_min',
110
+ # 'pm10_avg',
111
+ # 'pm10_max',
112
+ # 'pm10_min',
113
+ # 'pm25_avg',
114
+ # 'pm25_max',
115
+ # 'pm25_min',
116
+ # 'uvi_avg',
117
+ # 'uvi_max',
118
+ # 'uvi_min',
119
+ # 'pm25_min'
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
+
131
+ def get_weather_json(city, date, WEATHER_API_KEY):
132
+ 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()
133
+
134
+
135
+ def get_weather_data(city_name, date):
136
+ WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')
137
+ json = get_weather_json(city_name, date, WEATHER_API_KEY)
138
+ data = json['days'][0]
139
+
140
+ return [
141
+ # json['address'].capitalize(),
142
+ data['datetime'],
143
+ data['tempmax'],
144
+ data['tempmin'],
145
+ data['temp'],
146
+ # data['feelslikemax'],
147
+ # data['feelslikemin'],
148
+ # data['feelslike'],
149
+ data['dew'],
150
+ data['humidity'],
151
+ data['precip'],
152
+ # data['precipprob'],
153
+ data['precipcover'],
154
+ data['snow'],
155
+ data['snowdepth'],
156
+ data['windgust'],
157
+ data['windspeed'],
158
+ data['winddir'],
159
+ # data['pressure'],
160
+ data['cloudcover'],
161
+ data['visibility'],
162
+ # data['solarradiation'],
163
+ # data['solarenergy'],
164
+ int(data['uvindex']),
165
+ data['conditions']
166
+ ]
167
+
168
+
169
+ def get_weather_df(data):
170
+ col_names = [
171
+ # 'city',
172
+ 'date',
173
+ 'tempmax',
174
+ 'tempmin',
175
+ 'temp',
176
+ # 'feelslikemax',
177
+ # 'feelslikemin',
178
+ # 'feelslike',
179
+ 'dew',
180
+ 'humidity',
181
+ 'precip',
182
+ # 'precipprob',
183
+ 'precipcover',
184
+ 'snow',
185
+ 'snowdepth',
186
+ 'windgust',
187
+ 'windspeed',
188
+ 'winddir',
189
+ # 'pressure',
190
+ 'cloudcover',
191
+ 'visibility',
192
+ # 'solarradiation',
193
+ # 'solarenergy',
194
+ 'uvindex',
195
+ 'conditions'
196
+ ]
197
+
198
+ new_data = pd.DataFrame(
199
+ data,
200
+ columns=col_names
201
+ )
202
+ new_data.date = new_data.date.apply(timestamp_2_time)
203
+
204
+ return new_data
205
+
206
+ def timestamp_2_time(x):
207
+ dt_obj = datetime.strptime(str(x), '%Y-%m-%d')
208
+ dt_obj = dt_obj.timestamp() * 1000
209
+ return int(dt_obj)