howlbz commited on
Commit
e85573a
1 Parent(s): 844c121

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +140 -0
  2. functions.py +206 -0
  3. requirements.txt +11 -0
app.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import hopsworks
3
+ import joblib
4
+ import pandas as pd
5
+
6
+ import numpy as np
7
+ import folium
8
+ from streamlit_folium import st_folium, folium_static
9
+ import json
10
+ import time
11
+ from datetime import timedelta, datetime
12
+ from branca.element import Figure
13
+
14
+ from functions import decode_features, get_model
15
+
16
+
17
+ def fancy_header(text, font_size=24):
18
+ res = f'<span style="color:#ff5f27; font-size: {font_size}px;">{text}</span>'
19
+ st.markdown(res, unsafe_allow_html=True )
20
+
21
+
22
+ st.title('⛅️Air Quality Prediction Project🌩')
23
+
24
+ progress_bar = st.sidebar.header('⚙️ Working Progress')
25
+ progress_bar = st.sidebar.progress(0)
26
+ st.write(36 * "-")
27
+ fancy_header('\n📡 Connecting to Hopsworks Feature Store...')
28
+
29
+ project = hopsworks.login()
30
+ fs = project.get_feature_store()
31
+ feature_view = fs.get_feature_view(
32
+ name = 'air_quality_fv',
33
+ version = 1
34
+ )
35
+
36
+ st.write("Successfully connected!✔️")
37
+ progress_bar.progress(20)
38
+
39
+ st.write(36 * "-")
40
+ fancy_header('\n☁️ Getting batch data from Feature Store...')
41
+
42
+ start_date = datetime.now() - timedelta(days=1)
43
+ start_time = int(start_date.timestamp()) * 1000
44
+
45
+ X = feature_view.get_batch_data(start_time=start_time)
46
+ progress_bar.progress(50)
47
+
48
+ latest_date_unix = str(X.date.values[0])[:10]
49
+ latest_date = time.ctime(int(latest_date_unix))
50
+
51
+ st.write(f"⏱ Data for {latest_date}")
52
+
53
+ X = X.drop(columns=["date"]).fillna(0)
54
+
55
+ data_to_display = decode_features(X, feature_view=feature_view)
56
+
57
+ progress_bar.progress(60)
58
+
59
+ st.write(36 * "-")
60
+ fancy_header(f"🗺 Processing the map...")
61
+
62
+ fig = Figure(width=550,height=350)
63
+
64
+ my_map = folium.Map(location=[58, 20], zoom_start=3.71)
65
+ fig.add_child(my_map)
66
+ folium.TileLayer('Stamen Terrain').add_to(my_map)
67
+ folium.TileLayer('Stamen Toner').add_to(my_map)
68
+ folium.TileLayer('Stamen Water Color').add_to(my_map)
69
+ folium.TileLayer('cartodbpositron').add_to(my_map)
70
+ folium.TileLayer('cartodbdark_matter').add_to(my_map)
71
+ folium.LayerControl().add_to(my_map)
72
+
73
+ data_to_display = data_to_display[["city", "temp", "humidity",
74
+ "conditions", "aqi"]]
75
+
76
+ cities_coords = {("Sundsvall", "Sweden"): [62.390811, 17.306927],
77
+ ("Stockholm", "Sweden"): [59.334591, 18.063240],
78
+ ("Malmo", "Sweden"): [55.604981, 13.003822]}
79
+
80
+ if "Kyiv" in data_to_display["city"]:
81
+ cities_coords[("Kyiv", "Ukraine")]: [50.450001, 30.523333]
82
+
83
+ data_to_display = data_to_display.set_index("city")
84
+
85
+ cols_names_dict = {"temp": "Temperature",
86
+ "humidity": "Humidity",
87
+ "conditions": "Conditions",
88
+ "aqi": "AQI"}
89
+
90
+ data_to_display = data_to_display.rename(columns=cols_names_dict)
91
+
92
+ cols_ = ["Temperature", "Humidity", "AQI"]
93
+ data_to_display[cols_] = data_to_display[cols_].apply(lambda x: round(x, 1))
94
+
95
+ for city, country in cities_coords:
96
+ text = f"""
97
+ <h4 style="color:green;">{city}</h4>
98
+ <h5 style="color":"green">
99
+ <table style="text-align: right;">
100
+ <tr>
101
+ <th>Country:</th>
102
+ <td><b>{country}</b></td>
103
+ </tr>
104
+ """
105
+ for column in data_to_display.columns:
106
+ text += f"""
107
+ <tr>
108
+ <th>{column}:</th>
109
+ <td>{data_to_display.loc[city][column]}</td>
110
+ </tr>"""
111
+ text += """</table>
112
+ </h5>"""
113
+
114
+ folium.Marker(
115
+ cities_coords[(city, country)], popup=text, tooltip=f"<strong>{city}</strong>"
116
+ ).add_to(my_map)
117
+
118
+
119
+ # call to render Folium map in Streamlit
120
+ folium_static(my_map)
121
+ progress_bar.progress(80)
122
+ st.sidebar.write("-" * 36)
123
+
124
+
125
+ model = get_model(project=project,
126
+ model_name="gradient_boost_model",
127
+ evaluation_metric="f1_score",
128
+ sort_metrics_by="max")
129
+
130
+ preds = model.predict(X)
131
+
132
+ cities = [city_tuple[0] for city_tuple in cities_coords.keys()]
133
+
134
+ next_day_date = datetime.today() + timedelta(days=1)
135
+ next_day = next_day_date.strftime ('%d/%m/%Y')
136
+ df = pd.DataFrame(data=preds, index=cities, columns=[f"AQI Predictions for {next_day}"], dtype=int)
137
+
138
+ st.sidebar.write(df)
139
+ progress_bar.progress(100)
140
+ st.button("Re-run")
functions.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is from the hopsworks-tutorials
2
+ # https://github.com/logicalclocks/hopsworks-tutorials/tree/master/advanced_tutorials/air_quality
3
+
4
+ from datetime import datetime
5
+ import requests
6
+ import os
7
+ import joblib
8
+ import pandas as pd
9
+
10
+ from dotenv import load_dotenv
11
+ load_dotenv()
12
+
13
+ def decode_features(df, feature_view):
14
+ """Decodes features in the input DataFrame using corresponding Hopsworks Feature Store transformation functions"""
15
+ df_res = df.copy()
16
+
17
+ import inspect
18
+
19
+
20
+ td_transformation_functions = feature_view._batch_scoring_server._transformation_functions
21
+
22
+ res = {}
23
+ for feature_name in td_transformation_functions:
24
+ if feature_name in df_res.columns:
25
+ td_transformation_function = td_transformation_functions[feature_name]
26
+ sig, foobar_locals = inspect.signature(td_transformation_function.transformation_fn), locals()
27
+ param_dict = dict([(param.name, param.default) for param in sig.parameters.values() if param.default != inspect._empty])
28
+ if td_transformation_function.name == "min_max_scaler":
29
+ df_res[feature_name] = df_res[feature_name].map(
30
+ lambda x: x * (param_dict["max_value"] - param_dict["min_value"]) + param_dict["min_value"])
31
+
32
+ elif td_transformation_function.name == "standard_scaler":
33
+ df_res[feature_name] = df_res[feature_name].map(
34
+ lambda x: x * param_dict['std_dev'] + param_dict["mean"])
35
+ elif td_transformation_function.name == "label_encoder":
36
+ dictionary = param_dict['value_to_index']
37
+ dictionary_ = {v: k for k, v in dictionary.items()}
38
+ df_res[feature_name] = df_res[feature_name].map(
39
+ lambda x: dictionary_[x])
40
+ return df_res
41
+
42
+
43
+ def get_model(project, model_name, evaluation_metric, sort_metrics_by):
44
+ """Retrieve desired model or download it from the Hopsworks Model Registry.
45
+ In second case, it will be physically downloaded to this directory"""
46
+ TARGET_FILE = "model.pkl"
47
+ list_of_files = [os.path.join(dirpath,filename) for dirpath, _, filenames \
48
+ in os.walk('.') for filename in filenames if filename == TARGET_FILE]
49
+
50
+ if list_of_files:
51
+ model_path = list_of_files[0]
52
+ model = joblib.load(model_path)
53
+ else:
54
+ if not os.path.exists(TARGET_FILE):
55
+ mr = project.get_model_registry()
56
+ # get best model based on custom metrics
57
+ model = mr.get_best_model(model_name,
58
+ evaluation_metric,
59
+ sort_metrics_by)
60
+ model_dir = model.download()
61
+ model = joblib.load(model_dir + "/model.pkl")
62
+
63
+ return model
64
+
65
+
66
+ def get_air_json(city_name, AIR_QUALITY_API_KEY):
67
+ return requests.get(f'https://api.waqi.info/feed/{city_name}/?token={AIR_QUALITY_API_KEY}').json()['data']
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
+ def get_air_quality_df(data):
97
+ col_names = [
98
+ 'city',
99
+ 'aqi',
100
+ 'date&time',
101
+ 'iaqi_h',
102
+ 'iaqi_p',
103
+ 'iaqi_pm10',
104
+ 'iaqi_t',
105
+ 'o3_avg',
106
+ 'o3_max',
107
+ 'o3_min',
108
+ 'pm10_avg',
109
+ 'pm10_max',
110
+ 'pm10_min',
111
+ 'pm25_avg',
112
+ 'pm25_max',
113
+ 'pm25_min',
114
+ # 'uvi_avg',
115
+ # 'uvi_max',
116
+ # 'uvi_min',
117
+ ]
118
+
119
+ new_data = pd.DataFrame(
120
+ data,
121
+ columns=col_names
122
+ )
123
+ new_data.date = new_data.date.apply(timestamp_2_time)
124
+
125
+ return new_data
126
+
127
+
128
+ def get_weather_json(city, date, WEATHER_API_KEY):
129
+ 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()
130
+
131
+
132
+ def get_weather_data(city_name, date):
133
+ WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')
134
+ json = get_weather_json(city_name, date, WEATHER_API_KEY)
135
+ data = json['days'][0]
136
+
137
+ return [
138
+ json['address'].capitalize(),
139
+ data['datetime'],
140
+ data['tempmax'],
141
+ data['tempmin'],
142
+ data['temp'],
143
+ data['feelslikemax'],
144
+ data['feelslikemin'],
145
+ data['feelslike'],
146
+ data['dew'],
147
+ data['humidity'],
148
+ data['precip'],
149
+ data['precipprob'],
150
+ data['precipcover'],
151
+ data['snow'],
152
+ data['snowdepth'],
153
+ data['windgust'],
154
+ data['windspeed'],
155
+ data['winddir'],
156
+ data['pressure'],
157
+ data['cloudcover'],
158
+ data['visibility'],
159
+ data['solarradiation'],
160
+ data['solarenergy'],
161
+ data['uvindex'],
162
+ data['conditions']
163
+ ]
164
+
165
+
166
+ def get_weather_df(data):
167
+ col_names = [
168
+ 'city',
169
+ 'date',
170
+ 'tempmax',
171
+ 'tempmin',
172
+ 'temp',
173
+ 'feelslikemax',
174
+ 'feelslikemin',
175
+ 'feelslike',
176
+ 'dew',
177
+ 'humidity',
178
+ 'precip',
179
+ 'precipprob',
180
+ 'precipcover',
181
+ 'snow',
182
+ 'snowdepth',
183
+ 'windgust',
184
+ 'windspeed',
185
+ 'winddir',
186
+ 'pressure',
187
+ 'cloudcover',
188
+ 'visibility',
189
+ 'solarradiation',
190
+ 'solarenergy',
191
+ 'uvindex',
192
+ 'conditions'
193
+ ]
194
+
195
+ new_data = pd.DataFrame(
196
+ data,
197
+ columns=col_names
198
+ )
199
+ new_data.date = new_data.date.apply(timestamp_2_time)
200
+
201
+ return new_data
202
+
203
+ def timestamp_2_time(x):
204
+ dt_obj = datetime.strptime(str(x), '%Y-%m-%d')
205
+ dt_obj = dt_obj.timestamp() * 1000
206
+ return int(dt_obj)
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ branca==0.6.0
2
+ folium==0.14.0
3
+ hopsworks==3.0.5
4
+ joblib==1.2.0
5
+ numpy==1.23.5
6
+ pandas==1.5.2
7
+ python-dotenv==0.21.0
8
+ requests==2.28.1
9
+ streamlit==1.17.0
10
+ streamlit_folium==0.10.0
11
+ dotenv