KAPtechies commited on
Commit
a23359c
·
verified ·
1 Parent(s): e48449f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -59
app.py CHANGED
@@ -1,69 +1,53 @@
 
1
  import gradio as gr
2
- import pandas as pd
3
- import numpy as np
4
- import matplotlib.pyplot as plt
5
- import seaborn as sns
6
- from sklearn.preprocessing import MinMaxScaler
7
- from tensorflow.keras.models import load_model
8
- from tensorflow.keras.models import load_model
9
- from tensorflow.keras.losses import MeanSquaredError
10
 
11
- # Load dataset
12
- df = pd.read_csv("TEMP_ANNUAL_SEASONAL_MEAN.csv")
 
 
13
 
14
- # Convert 'YEAR' to datetime and set as index
15
- df.columns = df.columns.str.upper()
16
- df['YEAR'] = pd.to_datetime(df['YEAR'], format='%Y')
17
- df.set_index('YEAR', inplace=True)
18
 
19
- # Select relevant temperature column
20
- temp_col = 'ANNUAL'
21
- df[temp_col] = pd.to_numeric(df[temp_col], errors='coerce') # Handle errors
22
- data = df[[temp_col]].dropna()
23
 
24
- # Normalize the data
25
- scaler = MinMaxScaler()
26
- data_scaled = scaler.fit_transform(data)
27
-
28
- from tensorflow.keras.models import load_model
29
- from tensorflow.keras.losses import MeanSquaredError
30
-
31
- # Load model with custom_objects
32
- model = load_model("climate_model.h5", custom_objects={"mse": MeanSquaredError()})
33
-
34
-
35
- # Prediction function
36
- def predict_temperature(year):
37
- year = int(year)
38
 
39
- # Generate input for LSTM
40
- sequence_length = 10
41
- last_seq = data_scaled[-sequence_length:].reshape(1, sequence_length, 1)
42
-
43
- # Predict
44
- prediction_scaled = model.predict(last_seq)
45
- predicted_temp = scaler.inverse_transform(prediction_scaled)[0][0]
 
 
 
 
 
 
 
 
 
 
46
 
47
- # Generate graph
48
- fig, ax = plt.subplots(figsize=(10, 5))
49
- ax.plot(df.index[-20:], df[temp_col][-20:], label="Actual", color='blue')
50
- ax.axvline(pd.Timestamp(year, 1, 1), color='red', linestyle='dashed', label="Predicted Year")
51
- ax.scatter(pd.Timestamp(year, 1, 1), predicted_temp, color='red', marker='o', label=f"Predicted: {predicted_temp:.2f}°C")
52
- ax.set_xlabel("Year")
53
- ax.set_ylabel("Temperature (°C)")
54
- ax.set_title("Actual vs Predicted Annual Mean Temperature in India")
55
- ax.legend()
56
 
57
- return predicted_temp, fig # Return numeric output and graph
58
 
59
  # Gradio Interface
60
- with gr.Blocks() as demo:
61
- gr.Markdown("## Climate Change Temperature Prediction")
62
- year_input = gr.Number(label="Enter Year ", value=0)
63
- predict_button = gr.Button("Predict")
64
- output_temp = gr.Number(label="Predicted Temperature (°C)")
65
- output_plot = gr.Plot()
66
-
67
- predict_button.click(predict_temperature, inputs=[year_input], outputs=[output_temp, output_plot])
68
-
69
- demo.launch()
 
1
+ import requests
2
  import gradio as gr
3
+ from datetime import datetime
 
 
 
 
 
 
 
4
 
5
+ # OpenWeather API details
6
+ BASE_URL = "http://api.openweathermap.org/data/2.5/forecast?"
7
+ API_KEY = "2682f6801720ebeb43c93ad55c826c5c"
8
+ DAYS = 5 # Free API allows only 5 days
9
 
10
+ def get_weather(city):
11
+ url = f"{BASE_URL}q={city}&appid={API_KEY}&units=metric"
12
+ response = requests.get(url).json()
 
13
 
14
+ # Error handling
15
+ if response.get("cod") != "200":
16
+ return "❌ **Invalid city name! Please enter a correct city.**"
 
17
 
18
+ weather_info = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
+ # Extracting one data point per day
21
+ for entry in response["list"]:
22
+ date = entry["dt_txt"].split(" ")[0] # Extract only the date part
23
+ if date not in weather_info: # Store only one entry per day
24
+ weather_info[date] = {
25
+ "Temperature": f"{entry['main']['temp']}°C",
26
+ "Humidity": f"{entry['main']['humidity']}%",
27
+ "Pressure": f"{entry['main']['pressure']} hPa",
28
+ "Wind Speed": f"{entry['wind']['speed']} m/s",
29
+ "Rain": f"{entry.get('rain', {}).get('3h', 0)} mm",
30
+ "Cloud Cover": f"{entry['clouds']['all']}%" # Extracting cloud data
31
+ }
32
+
33
+ # Format output as a Markdown table
34
+ markdown_output = "**📅 5-Day Weather Forecast**\n\n"
35
+ markdown_output += "| Date | Temperature | Humidity | Pressure | Wind Speed | Rain | Cloud Cover |\n"
36
+ markdown_output += "|------------|------------|----------|----------|------------|------|-------------|\n"
37
 
38
+ for date, details in weather_info.items():
39
+ markdown_output += f"| {date} | {details['Temperature']} | {details['Humidity']} | {details['Pressure']} | {details['Wind Speed']} | {details['Rain']} | {details['Cloud Cover']} |\n"
 
 
 
 
 
 
 
40
 
41
+ return markdown_output
42
 
43
  # Gradio Interface
44
+ iface = gr.Interface(
45
+ fn=get_weather,
46
+ inputs=gr.Textbox(label="Enter City Name"),
47
+ outputs=gr.Markdown(),
48
+ title="🌍 5-Day Weather Forecast",
49
+ description="Enter a city name to get temperature, humidity, pressure, wind speed, rain, and cloud cover data for the next **5 days**.",
50
+ )
51
+
52
+ if __name__ == "__main__":
53
+ iface.launch()