File size: 10,655 Bytes
1e216a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
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)