kk90ujhun commited on
Commit
195d038
·
1 Parent(s): 2f8315b

Create functions.py

Browse files
Files changed (1) hide show
  1. functions.py +208 -0
functions.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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
+ model_dir = model.download()
59
+ model = joblib.load(model_dir + "/model.pkl")
60
+
61
+ return model
62
+
63
+
64
+ def get_air_json(city_name, AIR_QUALITY_API_KEY):
65
+ return requests.get(f'https://api.waqi.info/feed/{city_name}/?token={AIR_QUALITY_API_KEY}').json()['data']
66
+
67
+
68
+ def get_air_quality_data(city_name):
69
+ AIR_QUALITY_API_KEY = os.getenv('AIR_QUALITY_API_KEY')
70
+ json = get_air_json(city_name, AIR_QUALITY_API_KEY)
71
+ iaqi = json['iaqi']
72
+ forecast = json['forecast']['daily']
73
+ print(city_name)
74
+ print(forecast.keys())
75
+ return [
76
+ # city_name,
77
+ # json['aqi'], # AQI
78
+ json['time']['s'][:10], # Date
79
+ float(iaqi['pm25']['v']),
80
+ float(iaqi['pm10']['v']),
81
+ iaqi['no2']['v']
82
+ # iaqi['t']['v']
83
+ # forecast['o3'][0]['avg'],
84
+ # forecast['o3'][0]['max'],
85
+ # forecast['o3'][0]['min'],
86
+ # forecast['pm10'][0]['avg'],
87
+ # forecast['pm10'][0]['max'],
88
+ # forecast['pm10'][0]['min'],
89
+ # forecast['pm25'][0]['avg'],
90
+ # forecast['pm25'][0]['max'],
91
+ # forecast['pm25'][0]['min'],
92
+ # forecast['uvi'][0]['avg'],
93
+ # forecast['uvi'][0]['max'],
94
+ # forecast['uvi'][0]['min']
95
+ # forecast['pm25'][0]['min']
96
+ ]
97
+
98
+ def get_air_quality_df(data):
99
+ col_names = [
100
+ # 'city',
101
+ # 'aqi',
102
+ 'date',
103
+ 'pm25',
104
+ 'pm10',
105
+ 'no2'
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
+ # 'pm25_min'
119
+ ]
120
+
121
+ new_data = pd.DataFrame(
122
+ data,
123
+ columns=col_names
124
+ )
125
+ new_data.date = new_data.date.apply(timestamp_2_time)
126
+
127
+ return new_data
128
+
129
+
130
+ def get_weather_json(city, date, WEATHER_API_KEY):
131
+ 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()
132
+
133
+
134
+ def get_weather_data(city_name, date):
135
+ WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')
136
+ json = get_weather_json(city_name, date, WEATHER_API_KEY)
137
+ data = json['days'][0]
138
+
139
+ return [
140
+ # json['address'].capitalize(),
141
+ data['datetime'],
142
+ data['tempmax'],
143
+ data['tempmin'],
144
+ data['temp'],
145
+ # data['feelslikemax'],
146
+ # data['feelslikemin'],
147
+ # data['feelslike'],
148
+ data['dew'],
149
+ data['humidity'],
150
+ data['precip'],
151
+ # data['precipprob'],
152
+ data['precipcover'],
153
+ data['snow'],
154
+ data['snowdepth'],
155
+ data['windgust'],
156
+ data['windspeed'],
157
+ data['winddir'],
158
+ # data['pressure'],
159
+ data['cloudcover'],
160
+ data['visibility'],
161
+ # data['solarradiation'],
162
+ # data['solarenergy'],
163
+ int(data['uvindex']),
164
+ data['conditions']
165
+ ]
166
+
167
+
168
+ def get_weather_df(data):
169
+ col_names = [
170
+ # 'city',
171
+ 'date',
172
+ 'tempmax',
173
+ 'tempmin',
174
+ 'temp',
175
+ # 'feelslikemax',
176
+ # 'feelslikemin',
177
+ # 'feelslike',
178
+ 'dew',
179
+ 'humidity',
180
+ 'precip',
181
+ # 'precipprob',
182
+ 'precipcover',
183
+ 'snow',
184
+ 'snowdepth',
185
+ 'windgust',
186
+ 'windspeed',
187
+ 'winddir',
188
+ # 'pressure',
189
+ 'cloudcover',
190
+ 'visibility',
191
+ # 'solarradiation',
192
+ # 'solarenergy',
193
+ 'uvindex',
194
+ 'conditions'
195
+ ]
196
+
197
+ new_data = pd.DataFrame(
198
+ data,
199
+ columns=col_names
200
+ )
201
+ new_data.date = new_data.date.apply(timestamp_2_time)
202
+
203
+ return new_data
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)