AQI_APP / app.py
WebashalarForML's picture
Upload 23 files
1e216a1 verified
raw
history blame
10.7 kB
import matplotlib
matplotlib.use('Agg') # Set non-GUI backend for Matplotlib
import tensorflow as tf
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from flask import Flask, render_template, request
from keras.models import model_from_json
import folium
import json
import requests
from pathlib import Path
from io import BytesIO
import base64
app = Flask(__name__)
# Load the model
def load_model(name):
with open(f"{name}.json", "r") as json_file:
loaded_model_json = json_file.read()
loaded_model = model_from_json(loaded_model_json)
weights_file = f"{name}.weights.h5"
if not Path(weights_file).is_file():
raise FileNotFoundError(f"Weight file {weights_file} not found.")
loaded_model.load_weights(weights_file)
print("Loaded model from disk")
return loaded_model
#MAP CREATING
# Function to create map
def create_map(df, predicted_wind_speed, map_file):
# Extract latitude, longitude, and actual wind speed
latitude = df['lat'].iloc[0]
longitude = df['lon'].iloc[0]
actual_wind_speed = df['wind_kph'].iloc[0]
# Ensure single numeric values for plotting
if isinstance(actual_wind_speed, (list, np.ndarray)):
actual_wind_speed = actual_wind_speed[0]
if isinstance(predicted_wind_speed, (list, np.ndarray)):
predicted_wind_speed = predicted_wind_speed[0]
# Create folium map
m = folium.Map(location=[latitude, longitude], zoom_start=10)
# Create a bar chart comparing actual and predicted wind speeds
fig, ax = plt.subplots(figsize=(3, 3))
bars = ax.bar(['Actual', 'Predicted'], [actual_wind_speed, predicted_wind_speed], color=['blue', 'green'])
ax.set_ylabel('Wind Speed (km/h)')
ax.set_title('Wind Speed Comparison')
# Add labels inside each bar
for bar in bars:
yval = bar.get_height() # Get the height of each bar (wind speed value)
# Position the label inside the bar, slightly adjusted to avoid overlap with the top
ax.text(bar.get_x() + bar.get_width() / 2, yval / 2, round(yval, 2), ha='center', va='center', color='white')
# Adjust layout
plt.tight_layout()
# Save chart to a BytesIO buffer in PNG format and encode to base64
buffer = BytesIO()
plt.savefig(buffer, format="png")
plt.close(fig)
buffer.seek(0)
image_base64 = base64.b64encode(buffer.read()).decode('utf-8')
# HTML for the popup with base64 image
popup_html = f'<img src="data:image/png;base64,{image_base64}" alt="Wind Speed Comparison">'
popup = folium.Popup(html=popup_html, max_width=300)
# Add a marker to the map with popup containing the chart
folium.Marker(
location=[latitude, longitude],
popup=popup,
tooltip=df['location'].iloc[0]
).add_to(m)
# Save the folium map as an HTML file
m.save(map_file)
model = load_model('Wind_Model_New_v1')
# Route to input form
@app.route('/')
def index():
return render_template('index.html')
# Prediction route
@app.route('/predict', methods=['POST'])
def predict():
latitude = float(request.form['latitude'])
longitude = float(request.form['longitude'])
api_key = "846ca0bb2fa144cdb7195352240711"
base_url = "http://api.weatherapi.com/v1/current.json"
params = {"key": api_key, "q": f"{latitude},{longitude}"}
response = requests.get(base_url, params=params)
if response.status_code == 200:
current_weather = response.json()
extracted_data = {
'location': current_weather['location']['name'],
'lat': latitude,
'lon': longitude,
'date': current_weather['location']['localtime'].split()[0],
'time': current_weather['location']['localtime'],
'temp_c': current_weather['current']['temp_c'],
'temp_f': current_weather['current']['temp_f'],
'is_day': current_weather['current']['is_day'],
'condition': current_weather['current']['condition']['text'],
'wind_mph': current_weather['current']['wind_mph'],
'wind_kph': current_weather['current']['wind_kph'],
'humidity': current_weather['current']['humidity'],
'cloud': current_weather['current']['cloud'],
'feelslike_c': current_weather['current']['feelslike_c'],
'feelslike_f': current_weather['current']['feelslike_f'],
'windchill_c': current_weather['current']['windchill_c'],
'windchill_f': current_weather['current']['windchill_f'],
'heatindex_c': current_weather['current']['heatindex_c'],
'heatindex_f': current_weather['current']['heatindex_f'],
'dewpoint_c': current_weather['current']['dewpoint_c'],
'dewpoint_f': current_weather['current']['dewpoint_f'],
'vis_km': current_weather['current']['vis_km'],
'vis_miles': current_weather['current']['vis_miles'],
'gust_mph': current_weather['current']['gust_mph'],
'gust_kph': current_weather['current']['gust_kph'],
'uv': current_weather['current']['uv']
}
df = pd.DataFrame([extracted_data])
print("dataframe",df)
df['time'] = pd.to_datetime(df['time'])
df['day'] = df['time'].dt.day
df['month'] = df['time'].dt.month
df['hour'] = df['time'].dt.hour
dx=df[['temp_c', 'temp_f', 'is_day','wind_mph', 'wind_kph', 'humidity', 'cloud', 'feelslike_c',
'feelslike_f', 'windchill_c', 'windchill_f', 'heatindex_c','heatindex_f', 'dewpoint_c',
'dewpoint_f', 'vis_km', 'vis_miles','gust_mph', 'gust_kph', 'uv', 'day', 'month', 'hour']]
x=dx.drop(['wind_mph', 'wind_kph'],axis=1)
x_unk = np.array(x)
x_unk = x_unk / 100
predictions = model.predict(x_unk)
predicted_wind_speed = predictions[0][0]
print("predictions",predictions)
map_file = "static/multiple_wind_speed_map.html"
create_map(df, predicted_wind_speed, map_file)
return render_template('results.html',
actual=df['wind_kph'][0],
predicted=predicted_wind_speed,
map_file='multiple_wind_speed_map.html')
else:
return "Failed to retrieve weather data."
# forcast
@app.route('/forcast', methods=['POST'])
def forcast():
latitude = float(request.form['latitude'])
longitude = float(request.form['longitude'])
api_key = "846ca0bb2fa144cdb7195352240711"
base_url = "http://api.weatherapi.com/v1/forecast.json"
params = {
"key": api_key,
"q": f"{latitude},{longitude}",
"days": 1 # Fetch forecast for 1 day
}
response = requests.get(base_url, params=params)
extracted_data = {}
if response.status_code == 200:
data = response.json()
for location in data:
location_name = data['location']['name']
forecast_days = data['forecast']['forecastday']
# Loop through each day in forecastdays
for day in forecast_days:
date = day['date']
hours = day['hour']
# Extract hourly data for each hour
for hour_data in hours:
# Add extra details (date, location) for each hourly data
extracted_data={
"location": location_name,
"lat": latitude,
"lon": longitude,
"date": date,
"time": hour_data["time"],
"temp_c": hour_data["temp_c"],
"temp_f": hour_data["temp_f"],
"is_day": hour_data["is_day"],
"condition": hour_data["condition"]["text"],
"wind_mph": hour_data["wind_mph"],
"wind_kph": hour_data["wind_kph"],
"humidity": hour_data["humidity"],
"cloud": hour_data["cloud"],
"feelslike_c": hour_data["feelslike_c"],
"feelslike_f": hour_data["feelslike_f"],
"windchill_c": hour_data["windchill_c"],
"windchill_f": hour_data["windchill_f"],
"heatindex_c": hour_data["heatindex_c"],
"heatindex_f": hour_data["heatindex_f"],
"dewpoint_c": hour_data["dewpoint_c"],
"dewpoint_f": hour_data["dewpoint_f"],
"vis_km": hour_data["vis_km"],
"vis_miles": hour_data["vis_miles"],
"gust_mph": hour_data["gust_mph"],
"gust_kph": hour_data["gust_kph"],
"uv": hour_data["uv"]
}
# Convert extracted data into a DataFrame
df = pd.DataFrame([extracted_data])
print("dataframe", df)
# Extracting additional date/time features
df['time']=pd.to_datetime(df['time'])
df['datetime']=pd.to_datetime(df['time'])
df['day'] = df['datetime'].dt.day # Extracts day of the month
df['month'] = df['datetime'].dt.month # Extracts month
df['hour'] = df['datetime'].dt.hour
# Prepare features for prediction
dx=df[['temp_c', 'temp_f', 'is_day','wind_mph', 'wind_kph', 'humidity', 'cloud', 'feelslike_c','feelslike_f', 'windchill_c', 'windchill_f', 'heatindex_c','heatindex_f', 'dewpoint_c', 'dewpoint_f', 'vis_km', 'vis_miles','gust_mph', 'gust_kph', 'uv', 'day', 'month', 'hour']]
x = dx.drop(['wind_mph', 'wind_kph'], axis=1)
x_unk = np.array(x)
x_unk = x_unk / 110
predictions = model.predict(x_unk)
predicted_wind_speed = predictions[0][0]
print("predictions",predictions)
map_file = "static/multiple_wind_speed_map.html"
create_map(df, predicted_wind_speed, map_file)
return render_template('results.html',
actual=df['wind_kph'][0],
predicted=predicted_wind_speed,
map_file='multiple_wind_speed_map.html')
else:
return "Failed to retrieve weather data."
if __name__ == '__main__':
app.run(debug=True)