Yasaman commited on
Commit
02cdee1
1 Parent(s): 6380fd4

Create function.py

Browse files
Files changed (1) hide show
  1. function.py +180 -0
function.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import os
3
+ import pandas as pd
4
+ import datetime
5
+ import numpy as np
6
+ from sklearn.preprocessing import OrdinalEncoder
7
+ from dotenv import load_dotenv
8
+ load_dotenv()
9
+
10
+
11
+ ## TODO: write function to display the color coding of the categoies both in the df and as a guide.
12
+ #sg like:
13
+ def color_aq(val):
14
+ color = 'green' if val else 'red'
15
+ return f'background-color: {color}'
16
+ # but better
17
+
18
+
19
+ def get_air_quality_data(station_name):
20
+ AIR_QUALITY_API_KEY = os.getenv('AIR_QUALITY_API_KEY')
21
+ request_value = f'https://api.waqi.info/feed/{station_name}/?token={AIR_QUALITY_API_KEY}'
22
+ answer = requests.get(request_value).json()["data"]
23
+ forecast = answer['forecast']['daily']
24
+ return [
25
+ answer["time"]["s"][:10], # Date
26
+ int(forecast['pm25'][0]['avg']), # avg predicted pm25
27
+ int(forecast['pm10'][0]['avg']), # avg predicted pm10
28
+ max(int(forecast['pm25'][0]['avg']), int(forecast['pm10'][0]['avg'])) # avg predicted aqi
29
+ ]
30
+
31
+ def get_air_quality_df(data):
32
+ col_names = [
33
+ 'date',
34
+ 'pm25',
35
+ 'pm10',
36
+ 'aqi'
37
+ ]
38
+
39
+ new_data = pd.DataFrame(
40
+ data
41
+ ).T
42
+ new_data.columns = col_names
43
+ new_data['pm25'] = pd.to_numeric(new_data['pm25'])
44
+ new_data['pm10'] = pd.to_numeric(new_data['pm10'])
45
+ new_data['aqi'] = pd.to_numeric(new_data['aqi'])
46
+
47
+ return new_data
48
+
49
+
50
+ def get_weather_data_daily(city):
51
+ WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')
52
+ answer = requests.get(f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/{city}/today?unitGroup=metric&include=days&key={WEATHER_API_KEY}&contentType=json').json()
53
+ data = answer['days'][0]
54
+ return [
55
+ answer['address'].lower(),
56
+ data['datetime'],
57
+ data['tempmax'],
58
+ data['tempmin'],
59
+ data['temp'],
60
+ data['feelslikemax'],
61
+ data['feelslikemin'],
62
+ data['feelslike'],
63
+ data['dew'],
64
+ data['humidity'],
65
+ data['precip'],
66
+ data['precipprob'],
67
+ data['precipcover'],
68
+ data['snow'],
69
+ data['snowdepth'],
70
+ data['windgust'],
71
+ data['windspeed'],
72
+ data['winddir'],
73
+ data['pressure'],
74
+ data['cloudcover'],
75
+ data['visibility'],
76
+ data['solarradiation'],
77
+ data['solarenergy'],
78
+ data['uvindex'],
79
+ data['conditions']
80
+ ]
81
+
82
+ def get_weather_data_weekly(city: str, start_date: datetime) -> pd.DataFrame:
83
+ WEATHER_API_KEY = os.getenv('WEATHER_API_KEY')
84
+ end_date = f"{start_date + datetime.timedelta(days=6):%Y-%m-%d}"
85
+ answer = requests.get(f'https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/{city}/{start_date}/{end_date}?unitGroup=metric&include=days&key={WEATHER_API_KEY}&contentType=json').json()
86
+ weather_data = answer['days']
87
+ final_df = pd.DataFrame()
88
+
89
+ for i in range(7):
90
+ data = weather_data[i]
91
+ list_of_data = [
92
+ answer['address'].lower(),
93
+ data['datetime'],
94
+ data['tempmax'],
95
+ data['tempmin'],
96
+ data['temp'],
97
+ data['feelslikemax'],
98
+ data['feelslikemin'],
99
+ data['feelslike'],
100
+ data['dew'],
101
+ data['humidity'],
102
+ data['precip'],
103
+ data['precipprob'],
104
+ data['precipcover'],
105
+ data['snow'],
106
+ data['snowdepth'],
107
+ data['windgust'],
108
+ data['windspeed'],
109
+ data['winddir'],
110
+ data['pressure'],
111
+ data['cloudcover'],
112
+ data['visibility'],
113
+ data['solarradiation'],
114
+ data['solarenergy'],
115
+ data['uvindex'],
116
+ data['conditions']
117
+ ]
118
+ weather_df = get_weather_df(list_of_data)
119
+ final_df = pd.concat([final_df, weather_df])
120
+ return final_df
121
+
122
+ def get_weather_df(data):
123
+ col_names = [
124
+ 'name',
125
+ 'date',
126
+ 'tempmax',
127
+ 'tempmin',
128
+ 'temp',
129
+ 'feelslikemax',
130
+ 'feelslikemin',
131
+ 'feelslike',
132
+ 'dew',
133
+ 'humidity',
134
+ 'precip',
135
+ 'precipprob',
136
+ 'precipcover',
137
+ 'snow',
138
+ 'snowdepth',
139
+ 'windgust',
140
+ 'windspeed',
141
+ 'winddir',
142
+ 'pressure',
143
+ 'cloudcover',
144
+ 'visibility',
145
+ 'solarradiation',
146
+ 'solarenergy',
147
+ 'uvindex',
148
+ 'conditions'
149
+ ]
150
+
151
+ new_data = pd.DataFrame(
152
+ data
153
+ ).T
154
+ new_data.columns = col_names
155
+ for col in col_names:
156
+ if col not in ['name', 'date', 'conditions']:
157
+ new_data[col] = pd.to_numeric(new_data[col])
158
+
159
+ return new_data
160
+
161
+ def data_encoder(X):
162
+ X.drop(columns=['date', 'name'], inplace=True)
163
+ X['conditions'] = OrdinalEncoder().fit_transform(X[['conditions']])
164
+ return X
165
+
166
+ def get_aplevel(temps:np.ndarray, table:list):
167
+ boundary_list = np.array([0, 50, 100, 150, 200, 300]) # assert temps.shape == [x, 1]
168
+ redf = np.logical_not(temps<=boundary_list) # temps.shape[0] x boundary_list.shape[0] ndarray
169
+ hift = np.concatenate((np.roll(redf, -1)[:, :-1], np.full((temps.shape[0], 1), False)), axis = 1)
170
+ cat = np.nonzero(np.not_equal(redf,hift))
171
+
172
+ level = [table[el] for el in cat[1]]
173
+ return level
174
+
175
+ def get_color(level:list):
176
+ air_pollution_level = ['Good', 'Moderate', 'Unhealthy for sensitive Groups','Unhealthy' ,'Very Unhealthy', 'Hazardous']
177
+ color_list = ["Green", "Yellow", "DarkOrange", "Red", "Purple", "DarkRed"]
178
+ ind = [air_pollution_level.index(lel) for lel in level]
179
+ text = [f"color:{color_list[idex]};" for idex in ind]
180
+ return text