PKaushik commited on
Commit
14f4b1a
1 Parent(s): 28c99a7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +333 -0
app.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ from sklearn.model_selection import train_test_split
4
+ import pickle
5
+ from datetime import datetime, timedelta
6
+ import tensorflow as tf
7
+ from sklearn.preprocessing import MinMaxScaler
8
+ import json
9
+ import requests
10
+ import gradio as gr
11
+ import os.path
12
+ import matplotlib.pyplot as plt
13
+ import tempfile
14
+
15
+ data=pd.read_csv("weatherdatafinal.csv")
16
+
17
+ def add_daytime_column(data):
18
+ data['sunrise'] = pd.to_datetime(data['sunrise'])
19
+ data['sunset'] = pd.to_datetime(data['sunset'])
20
+
21
+ data['daytime'] = (data['sunset'] - data['sunrise']).dt.total_seconds() / 3600.0
22
+
23
+ return data
24
+
25
+ data=add_daytime_column(data)
26
+
27
+ data = data.drop(columns=['name','datetime', 'severerisk', 'conditions', 'description', 'icon', 'stations','snow','snowdepth','sunrise','sunset','precip'])
28
+ data['preciptype'] = data['preciptype'].fillna(0)
29
+ data['preciptype'] = data['preciptype'].replace({'rain': 1, 'rain,snow': 2, 'snow': 3, 'rain,freezingrain,snow':3})
30
+ data['windgust'] = data['windgust'].fillna(data['windgust'].median())
31
+ data['sealevelpressure'] = data['sealevelpressure'].fillna(data['sealevelpressure'].median())
32
+ data['pressure'] = data['sealevelpressure']
33
+ data=data.drop("sealevelpressure", axis=1)
34
+ feature_names = list(data.columns)
35
+ def train_model(ideal_max_temp, ideal_min_temp, ideal_humidity):
36
+
37
+
38
+ ideal_weights = {
39
+ 'tempmax': 6,
40
+ 'tempmin': 6,
41
+ 'temp': 6,
42
+ 'humidity': 2,
43
+ 'windspeed': 3,
44
+ 'windgust': 1.5,
45
+ 'cloudcover': 3,
46
+ 'daytime': 1,
47
+ 'precipprob': 1.5,
48
+ 'visibility': 1,
49
+ 'stability': 1
50
+ }
51
+
52
+ def normalize(value, min_value, max_value):
53
+ return (value - min_value) / (max_value - min_value)
54
+
55
+ for idx, row in data.iterrows():
56
+ tempmax_score = 1-normalize(abs(ideal_max_temp - row['tempmax']), min(data['tempmax']), max(data['tempmax']))
57
+ tempmin_score = 1-normalize(abs(ideal_min_temp - row['tempmin']), min(data['tempmin']), max(data['tempmin']))
58
+ temp_score = 1-normalize(abs(((ideal_max_temp + ideal_min_temp) / 2) - row['temp']), min(data['temp']), max(data['temp']))
59
+ stability_score = 1-normalize(abs(row['tempmax'] - row['tempmin']), min(data['tempmin']), max(data['tempmax']))
60
+ humidity_score = 1-normalize(abs(ideal_humidity - row['humidity']), min(data['humidity']), max(data['humidity']))
61
+ windspeed_score = 1-normalize(row['windspeed'], min(data['windspeed']), max(data['windspeed']))
62
+ windgust_score = 1-normalize(row['windgust'], min(data['windgust']), max(data['windgust']))
63
+ cloudcover_score = 1-normalize(row['cloudcover'], min(data['cloudcover']), max(data['cloudcover']))
64
+ daytime_score = normalize(row['daytime'], min(data['daytime']), max(data['daytime']))
65
+ precipprob_score = 1-normalize(row['precipprob'], min(data['precipprob']), max(data['precipprob']))
66
+ visibility_score = normalize(row['visibility'], min(data['visibility']), max(data['visibility']))
67
+
68
+ scores = [
69
+ tempmax_score * ideal_weights['tempmax'],
70
+ tempmin_score * ideal_weights['tempmin'],
71
+ temp_score * ideal_weights['temp'],
72
+ humidity_score * ideal_weights['humidity'],
73
+ windspeed_score * ideal_weights['windspeed'],
74
+ windgust_score * ideal_weights['windgust'],
75
+ cloudcover_score * ideal_weights['cloudcover'],
76
+ daytime_score * ideal_weights['daytime'],
77
+ precipprob_score * ideal_weights['precipprob'],
78
+ visibility_score * ideal_weights['visibility'],
79
+ stability_score * ideal_weights['stability']
80
+ ]
81
+
82
+ daily_score = np.mean(scores)
83
+ data.loc[idx, 'daily_score'] = daily_score
84
+
85
+
86
+
87
+ scaler = MinMaxScaler(feature_range=(0, 95))
88
+
89
+ scaled_scores = scaler.fit_transform(data[['daily_score']])
90
+
91
+ data['daily_score'] = scaled_scores
92
+
93
+ X_train, X_test, y_train, y_test = train_test_split(data.drop('daily_score', axis=1), data['daily_score'], test_size=0.3, random_state=42)
94
+
95
+ scaler = MinMaxScaler()
96
+ X_train = scaler.fit_transform(X_train)
97
+ X_test = scaler.transform(X_test)
98
+
99
+ model = tf.keras.Sequential([
100
+ tf.keras.layers.Dense(128, activation='relu', input_shape=(X_train.shape[1],)),
101
+ tf.keras.layers.BatchNormalization(),
102
+ tf.keras.layers.Dense(64, activation='relu'),
103
+ tf.keras.layers.BatchNormalization(),
104
+ tf.keras.layers.Dropout(0.1),
105
+ tf.keras.layers.Dense(32, activation='relu'),
106
+ tf.keras.layers.BatchNormalization(),
107
+ tf.keras.layers.Dropout(0.1),
108
+ tf.keras.layers.Dense(16, activation='relu'),
109
+ tf.keras.layers.BatchNormalization(),
110
+ tf.keras.layers.Dropout(0.1),
111
+ tf.keras.layers.Dense(1)
112
+ ])
113
+
114
+ model.compile(loss='mse', optimizer=tf.keras.optimizers.Adam(learning_rate=0.001), metrics=['mse', 'mae', 'msle'])
115
+
116
+ early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_mse', patience=20, restore_best_weights=True)
117
+
118
+ history = model.fit(X_train, y_train, epochs=200, batch_size=32, validation_split=0.2, callbacks=[early_stop])
119
+
120
+ model.save('trainedmodel.h5')
121
+ with open('scaler.pkl', 'wb') as f:
122
+ pickle.dump(scaler, f)
123
+
124
+ return "Model trained based on your preferences."
125
+
126
+
127
+
128
+ def predict_weather(Location, Day):
129
+
130
+ model = tf.keras.models.load_model('trainedmodel.h5')
131
+ with open('scaler.pkl', 'rb') as f:
132
+ scaler = pickle.load(f)
133
+
134
+
135
+ prediction_day = Day.strip().lower()
136
+ if prediction_day == "yesterday":
137
+ day = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
138
+ elif prediction_day == "today":
139
+ day = datetime.now().strftime("%Y-%m-%d")
140
+ elif prediction_day == "tomorrow":
141
+ day = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
142
+ else:
143
+ print("Invalid prediction day. Defaulting to today.")
144
+ day = datetime.now().strftime("%Y-%m-%d")
145
+
146
+ url = f"https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/{Location}/{day}/{day}?unitGroup=metric&include=hours&key=TDAK3FZB5KTLU64J25LPTQ38Q&contentType=json"
147
+ response = requests.get(url)
148
+ urldata= response.json()
149
+ def add_daytime_column(urldata):
150
+ urldata['days'][0]['sunrise'] = pd.to_datetime(urldata['days'][0]['sunrise'])
151
+ urldata['days'][0]['sunset'] = pd.to_datetime(urldata['days'][0]['sunset'])
152
+ urldata['days'][0]['daytime'] = (urldata['days'][0]['sunset'] - urldata['days'][0]['sunrise']).total_seconds() / 3600.0
153
+ return urldata
154
+
155
+ urldata=add_daytime_column(urldata)
156
+
157
+ def preprocess_preciptype(urldata):
158
+ preciptype_dict = {'rain': 1, 'rain,snow': 2, 'snow': 3, 'rain,freezingrain,snow': 4,'None':0}
159
+
160
+ for day in urldata['days']:
161
+ if day.get('preciptype') is not None:
162
+ preciptype_str = day['preciptype'][0]
163
+ preciptype_code = preciptype_dict.get(preciptype_str, 0)
164
+ day['preciptype'] = preciptype_code
165
+ else:
166
+ day['preciptype'] = 0
167
+
168
+ return urldata
169
+
170
+ def replace_nan_with_median(urldata, data):
171
+ for col in ['solarradiation', 'solarenergy', 'uvindex']:
172
+ urldata['days'][0][col] = urldata['days'][0][col] or np.nan
173
+
174
+ for col in ['solarradiation', 'solarenergy', 'uvindex']:
175
+ if np.isnan(urldata['days'][0][col]):
176
+ urldata['days'][0][col] = data[col].median()
177
+
178
+ return urldata
179
+
180
+ urldata=replace_nan_with_median(urldata,data)
181
+ urldata=preprocess_preciptype(urldata)
182
+
183
+ def mean(data, key):
184
+ values = [hour[key] for hour in data]
185
+ return sum(values) / len(values)
186
+
187
+ hours_data = urldata["days"][0]["hours"][6:24]
188
+ day_data = urldata['days'][0]
189
+
190
+ new_data = {
191
+ 'tempmax': [day_data['tempmax']],
192
+ 'tempmin': [day_data['tempmin']],
193
+ 'temp': [mean(hours_data, "temp")],
194
+ 'feelslikemax': [day_data['feelslikemax']],
195
+ 'feelslikemin': [day_data['feelslikemin']],
196
+ 'feelslike': [mean(hours_data, "feelslike")],
197
+ 'dew': [mean(hours_data, "dew")],
198
+ 'humidity': [mean(hours_data, "humidity")],
199
+ 'precipprob': [mean(hours_data, "precipprob")],
200
+ 'precipcover': [day_data['precipcover']],
201
+ 'preciptype': [day_data['preciptype']],
202
+ 'windgust': [mean(hours_data, "windgust")],
203
+ 'windspeed': [mean(hours_data, "windspeed")],
204
+ 'winddir': [day_data['winddir']],
205
+ 'pressure': [mean(hours_data, "pressure")],
206
+ 'cloudcover': [mean(hours_data, "cloudcover")],
207
+ 'visibility': [mean(hours_data, "visibility")],
208
+ 'solarradiation': [day_data['solarradiation']],
209
+ 'solarenergy': [day_data['solarenergy']],
210
+ 'uvindex': [day_data['uvindex']],
211
+ 'moonphase': [day_data['moonphase']],
212
+ 'daytime': [day_data['daytime']]}
213
+
214
+ input_data = pd.DataFrame(new_data)
215
+ input_data = input_data[feature_names]
216
+ input_data = scaler.transform(input_data)
217
+ input_data = input_data.reshape(1, -1)
218
+
219
+
220
+ predictions = model.predict(input_data)
221
+ hourly_scores = []
222
+
223
+ new_data_hour = {
224
+ 'tempmin': day_data['tempmin'],
225
+ 'feelslikemin': day_data['feelslikemin'],
226
+ 'precipcover': day_data['precipcover'],
227
+ 'moonphase': day_data['moonphase'],
228
+ 'daytime': day_data['daytime']
229
+ }
230
+
231
+ for hour_data in hours_data:
232
+ new_data_hour.update({
233
+ 'tempmax': hour_data['temp'],
234
+ 'feelslikemax': hour_data['feelslike'],
235
+ 'temp': hour_data['temp'],
236
+ 'feelslike': hour_data['feelslike'],
237
+ 'dew': hour_data['dew'],
238
+ 'humidity': hour_data['humidity'],
239
+ 'precipprob': hour_data['precipprob'],
240
+ 'preciptype': day_data['preciptype'],
241
+ 'windgust': hour_data['windgust'],
242
+ 'windspeed': hour_data['windspeed'],
243
+ 'winddir': hour_data['winddir'],
244
+ 'pressure': hour_data['pressure'],
245
+ 'cloudcover': hour_data['cloudcover'],
246
+ 'visibility': hour_data['visibility'],
247
+ 'solarradiation': hour_data['solarradiation'],
248
+ 'solarenergy': hour_data['solarenergy'],
249
+ 'uvindex': hour_data['uvindex']
250
+
251
+
252
+ })
253
+
254
+ input_data_hour = pd.DataFrame([new_data_hour])
255
+ input_data_hour = input_data_hour[feature_names]
256
+ input_data_hour = scaler.transform(input_data_hour)
257
+ input_data_hour = input_data_hour.reshape(1, -1)
258
+
259
+ predictions_hour = model.predict(input_data_hour)
260
+ hourly_scores.append(predictions_hour[0][0])
261
+ score = predictions[0][0]
262
+ if score >= 80:
263
+ message = "The weather is expected to be great based on your preferences!"
264
+ elif score >= 60:
265
+ message = "The weather is expected to be good based on your preferences."
266
+ else:
267
+ message = "The weather might not be ideal based on your preferences."
268
+
269
+ return score, message, hourly_scores
270
+
271
+ def main():
272
+ mode = gr.inputs.Radio(["Train Model", "Predict Weather"], label="Mode")
273
+ ideal_max_temp = gr.inputs.Slider(minimum=0, maximum=40, step=1, default=28, label="Ideal max temperature (°C)")
274
+ ideal_min_temp = gr.inputs.Slider(minimum=0, maximum=40, step=1, default=20, label="Ideal min temperature (°C)")
275
+ ideal_humidity = gr.inputs.Slider(minimum=40, maximum=100, step=1, default=70, label="Ideal humidity level (%)")
276
+ Location = gr.inputs.Textbox(placeholder="Enter your location (city name)")
277
+ Day = gr.inputs.Radio(choices=["yesterday", "today", "tomorrow"], label="Select day:")
278
+
279
+ outputs = [
280
+ gr.outputs.Textbox(label="Training Result"),
281
+ gr.outputs.Textbox(label="Predicted Daily Score"),
282
+ gr.outputs.Textbox(label="Message"),
283
+ gr.outputs.Image(type="filepath", label="Hourly Rating Plot")
284
+ ]
285
+
286
+
287
+ def wrapper(mode, ideal_max_temp, ideal_min_temp, ideal_humidity, Location, Day):
288
+ if mode == "Train Model":
289
+ result = train_model(ideal_max_temp, ideal_min_temp, ideal_humidity)
290
+ return result, None, None, None, None
291
+ else:
292
+ score, message, hourly_scores = predict_weather(Location, Day)
293
+ hours = range(6, 24)
294
+ plt.plot(hours,hourly_scores)
295
+ plt.xlabel('Hour of the Day')
296
+ plt.ylabel('Hourly Rating')
297
+ plt.xticks(range(6, 25, 1))
298
+ plt.xlim(6, 24)
299
+ plt.yticks(range(0, 101, 10))
300
+ plt.ylim(0, 100)
301
+ plt.title('Hourly Ratings Based On Your Preferences')
302
+ with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as temp_file:
303
+ plt.savefig(temp_file.name, format='png')
304
+ img_filepath = temp_file.name
305
+ plt.clf()
306
+
307
+ return None, score, message, img_filepath
308
+
309
+
310
+
311
+
312
+ interface = gr.Interface(
313
+ fn=wrapper,
314
+ inputs=[mode, ideal_max_temp, ideal_min_temp, ideal_humidity, Location, Day],
315
+ outputs=outputs,
316
+ title="Weather Rating",
317
+ description=(
318
+ "<b>WeatherApp.v1: Personalized Weather Predictions</b><br>"
319
+ "Designed to provide you with tailored weather forecasts, taking into account your preferences for maximum and minimum temperature, humidity, and other key factors. Our advanced algorithms calculate weather features using historical and real-time data, delivering a personalized weather score to help you plan your day with confidence.<br><br>"
320
+ "<b>How to use:</b><br>"
321
+ "1. Input your preferred maximum temperature, minimum temperature, and humidity.<br>"
322
+ "2. Train the model to adapt to your preferences.<br>"
323
+ "3. Receive personalized weather scores to better plan your day.<br><br>"
324
+ "Whether you're planning outdoor activities or just want to know how the day will feel, WeatherApp gives you a user-focused forecast for a more enjoyable experience."
325
+ ),
326
+ allow_flagging=False,
327
+ allow_screenshot=False
328
+ )
329
+
330
+ interface.launch()
331
+
332
+ if __name__ == "__main__":
333
+ main()