Snigs98 commited on
Commit
e3552a5
Β·
verified Β·
1 Parent(s): 91693d2

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -0
app.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import numpy as np
4
+ import pandas as pd
5
+ import gradio as gr
6
+ import zipfile
7
+ from sklearn.model_selection import train_test_split
8
+ from sklearn.preprocessing import LabelEncoder
9
+ from sklearn.ensemble import RandomForestRegressor
10
+
11
+ # Ensure required packages are installed
12
+ try:
13
+ import gradio as gr
14
+ except ImportError:
15
+ subprocess.run(["pip", "install", "gradio"], check=True)
16
+ import gradio as gr
17
+
18
+ # Define file paths
19
+ zip_file_path = "AI-powered Weather Forecasting.zip"
20
+ extract_folder = "weather_forecasting_dataset"
21
+
22
+ # Extract the ZIP file
23
+ with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
24
+ zip_ref.extractall(extract_folder)
25
+
26
+ # Locate CSV file
27
+ csv_file_path = os.path.join(extract_folder, "weatherHistory.csv")
28
+
29
+ # Load the dataset
30
+ df = pd.read_csv(csv_file_path)
31
+
32
+ # Convert 'Formatted Date' to datetime format
33
+ df['Formatted Date'] = pd.to_datetime(df['Formatted Date'], utc=True)
34
+ df.set_index('Formatted Date', inplace=True)
35
+
36
+ # βœ… Drop unnecessary columns
37
+ df.drop(columns=['Summary', 'Daily Summary', 'Apparent Temperature (C)'], inplace=True)
38
+
39
+ # βœ… Fill missing values in 'Precip Type'
40
+ df['Precip Type'].fillna("rain", inplace=True)
41
+
42
+ # βœ… Encode categorical variable 'Precip Type'
43
+ le = LabelEncoder()
44
+ df['Precip Type'] = le.fit_transform(df['Precip Type'])
45
+
46
+ # βœ… Feature engineering: Extract time-based features
47
+ df['Year'] = df.index.year
48
+ df['Month'] = df.index.month
49
+ df['Day'] = df.index.day
50
+ df['Hour'] = df.index.hour
51
+
52
+ # βœ… Print final feature names before training
53
+ print("βœ… Final Training Features:", df.columns.tolist())
54
+
55
+ # Define target variable (temperature prediction)
56
+ X = df.drop(columns=['Temperature (C)'])
57
+ y = df['Temperature (C)']
58
+
59
+ # βœ… Store feature names
60
+ feature_names = X.columns.tolist()
61
+ num_features = len(feature_names)
62
+
63
+ # βœ… Split data into training and testing sets
64
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
65
+
66
+ # βœ… Train RandomForestRegressor
67
+ model = RandomForestRegressor(n_estimators=500, random_state=42)
68
+ model.fit(X_train, y_train)
69
+
70
+ # βœ… Debug: Print feature importance
71
+ feature_importance = model.feature_importances_
72
+ print("πŸ“Š Feature Importance:", dict(zip(feature_names, feature_importance)))
73
+
74
+ # βœ… Define Prediction Function
75
+ def predict_temperature(precip_type, humidity, wind_speed, wind_bearing, visibility, pressure, loud_cover, year, month, day, hour):
76
+ try:
77
+ # βœ… Encode categorical variable
78
+ precip_type_encoded = le.transform([precip_type])[0]
79
+
80
+ # βœ… Create correct sample data (Ensures 12 Features)
81
+ sample_data = np.array([[precip_type_encoded, humidity, wind_speed, wind_bearing, visibility, pressure, loud_cover, year, month, day, hour]])
82
+
83
+ # βœ… Debug: Print input features before prediction
84
+ print("πŸ”Ή Prediction Input Features:", feature_names)
85
+ print("πŸ”Ή Prediction Input Sample:", sample_data)
86
+
87
+ # βœ… Fix feature mismatch by adding missing feature if needed
88
+ if sample_data.shape[1] < num_features:
89
+ missing_features = num_features - sample_data.shape[1]
90
+ sample_data = np.hstack((sample_data, np.zeros((1, missing_features))))
91
+ print(f"⚠️ Added {missing_features} missing features to match model training!")
92
+
93
+ # βœ… Debug: Print adjusted sample data
94
+ print("πŸ”Ή Adjusted Sample Data:", sample_data)
95
+
96
+ # βœ… Predict temperature
97
+ prediction = model.predict(sample_data)[0]
98
+
99
+ # βœ… Debug: Print final prediction value
100
+ print("πŸ”₯ Final Prediction:", prediction)
101
+
102
+ return f"Predicted Temperature: {prediction:.2f}Β°C"
103
+ except Exception as e:
104
+ return f"Error: {e}"
105
+
106
+ # βœ… Gradio UI
107
+ inputs = [
108
+ gr.Radio(["rain", "snow"], label="Precip Type"),
109
+ gr.Number(label="Humidity"),
110
+ gr.Number(label="Wind Speed (km/h)"),
111
+ gr.Number(label="Wind Bearing (degrees)"),
112
+ gr.Number(label="Visibility (km)"),
113
+ gr.Number(label="Pressure (millibars)"),
114
+ gr.Number(label="Loud Cover", value=0.0), # Default to 0 if always 0
115
+ gr.Number(label="Year"),
116
+ gr.Number(label="Month"),
117
+ gr.Number(label="Day"),
118
+ gr.Number(label="Hour"),
119
+ ]
120
+
121
+ demo = gr.Interface(fn=predict_temperature, inputs=inputs, outputs="text", title="AI-Powered Weather Forecasting")
122
+
123
+ demo.launch()