Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,117 +1,70 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
-
import plotly.express as px
|
| 4 |
import torch
|
| 5 |
import torch.nn as nn
|
| 6 |
import joblib
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
# Define your PyTorch model architecture (match what you trained)
|
| 14 |
-
class GridModel(nn.Module):
|
| 15 |
-
def __init__(self):
|
| 16 |
-
super(GridModel, self).__init__()
|
| 17 |
-
self.layers = nn.Sequential(
|
| 18 |
-
nn.Linear(5, 16),
|
| 19 |
-
nn.ReLU(),
|
| 20 |
-
nn.Linear(16, 8),
|
| 21 |
-
nn.ReLU(),
|
| 22 |
-
nn.Linear(8, 1),
|
| 23 |
-
nn.Sigmoid()
|
| 24 |
-
)
|
| 25 |
def forward(self, x):
|
| 26 |
-
return self.
|
| 27 |
|
| 28 |
-
# Load
|
| 29 |
@st.cache_resource
|
| 30 |
def load_model_and_scaler():
|
| 31 |
-
|
| 32 |
-
model
|
| 33 |
-
|
| 34 |
-
model.eval()
|
| 35 |
-
return model, scaler
|
| 36 |
-
|
| 37 |
-
model, scaler = load_model_and_scaler()
|
| 38 |
-
|
| 39 |
-
# Sidebar
|
| 40 |
-
st.sidebar.title("Smart Grid Dashboard")
|
| 41 |
-
location = st.sidebar.text_input("Enter Location", DEFAULT_LOCATION)
|
| 42 |
-
|
| 43 |
-
# Fetch and display weather data
|
| 44 |
-
weather = fetch_weather(API_KEY, location)
|
| 45 |
-
if weather:
|
| 46 |
-
st.sidebar.write(f"Temperature: {weather['temperature']} °C")
|
| 47 |
-
st.sidebar.write(f"Wind Speed: {weather['wind_speed']} m/s")
|
| 48 |
-
st.sidebar.write(f"Weather: {weather['weather']}")
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
# User upload section
|
| 54 |
-
uploaded_file = st.file_uploader("Upload your Smart Grid CSV file", type=["csv"])
|
| 55 |
-
|
| 56 |
-
if uploaded_file is not None:
|
| 57 |
-
data = pd.read_csv(uploaded_file)
|
| 58 |
-
st.success("File uploaded successfully!")
|
| 59 |
-
else:
|
| 60 |
-
st.info("No file uploaded. Using synthetic data for demonstration.")
|
| 61 |
-
data = generate_synthetic_data()
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
# Show plots (adjust columns if needed)
|
| 67 |
-
fig_load = px.line(data, x="timestamp", y="load", title="Load Over Time")
|
| 68 |
-
st.plotly_chart(fig_load)
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
st.plotly_chart(fig_renew)
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
|
| 83 |
-
|
| 84 |
-
features = data[['voltage', 'frequency', 'load', 'solar_gen', 'wind_gen']].values
|
| 85 |
-
X_scaled = scaler.transform(features)
|
| 86 |
-
inputs = torch.tensor(X_scaled, dtype=torch.float32)
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
outputs = model(inputs).numpy().flatten()
|
| 91 |
|
| 92 |
-
#
|
| 93 |
-
|
| 94 |
-
if
|
| 95 |
-
|
| 96 |
-
elif avg_output < 0.7:
|
| 97 |
-
status = "Warning"
|
| 98 |
else:
|
| 99 |
-
|
|
|
|
|
|
|
| 100 |
|
| 101 |
-
|
| 102 |
-
st.write(f"Predicted Grid Stability Status: **{status}** (Confidence: {avg_output:.2f})")
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
current_solar = data["solar_gen"].iloc[-1]
|
| 107 |
-
current_wind = data["wind_gen"].iloc[-1]
|
| 108 |
-
recommendation = optimize_load(current_demand, current_solar, current_wind)
|
| 109 |
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
st.write(f"Solar Output: {current_solar} kW")
|
| 113 |
-
st.write(f"Wind Output: {current_wind} kW")
|
| 114 |
-
st.write(f"Recommendation: {recommendation}")
|
| 115 |
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
|
|
|
| 3 |
import torch
|
| 4 |
import torch.nn as nn
|
| 5 |
import joblib
|
| 6 |
+
import plotly.express as px
|
| 7 |
+
import os
|
| 8 |
|
| 9 |
+
# Define the PyTorch model architecture (must match the one used during training)
|
| 10 |
+
class SmartGridModel(nn.Module):
|
| 11 |
+
def __init__(self, input_size, hidden_size=64, output_size=1):
|
| 12 |
+
super(SmartGridModel, self).__init__()
|
| 13 |
+
self.fc1 = nn.Linear(input_size, hidden_size)
|
| 14 |
+
self.relu = nn.ReLU()
|
| 15 |
+
self.fc2 = nn.Linear(hidden_size, output_size)
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
def forward(self, x):
|
| 18 |
+
return self.fc2(self.relu(self.fc1(x)))
|
| 19 |
|
| 20 |
+
# Load model and scaler with Streamlit caching
|
| 21 |
@st.cache_resource
|
| 22 |
def load_model_and_scaler():
|
| 23 |
+
# Ensure both files exist
|
| 24 |
+
if not os.path.exists("model.pth") or not os.path.exists("scaler.pkl"):
|
| 25 |
+
raise FileNotFoundError("Missing 'model.pth' or 'scaler.pkl'. Please upload them.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
model = SmartGridModel(input_size=5)
|
| 28 |
+
model.load_state_dict(torch.load("model.pth", map_location=torch.device("cpu")))
|
| 29 |
+
model.eval()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
scaler = joblib.load("scaler.pkl")
|
| 32 |
+
return model, scaler
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
+
# Predict function
|
| 35 |
+
def predict(data, model, scaler):
|
| 36 |
+
input_data = scaler.transform(data)
|
| 37 |
+
input_tensor = torch.tensor(input_data, dtype=torch.float32)
|
| 38 |
+
with torch.no_grad():
|
| 39 |
+
predictions = model(input_tensor).numpy()
|
| 40 |
+
return predictions
|
|
|
|
| 41 |
|
| 42 |
+
# Streamlit UI
|
| 43 |
+
st.title("🔌 Smart Grid Line Outage Detection")
|
| 44 |
+
st.markdown("Upload smart grid data and get outage predictions using a PyTorch model.")
|
| 45 |
|
| 46 |
+
uploaded_file = st.file_uploader("📁 Upload a CSV file", type=["csv"])
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
if uploaded_file:
|
| 49 |
+
df = pd.read_csv(uploaded_file)
|
|
|
|
| 50 |
|
| 51 |
+
# Ensure required columns exist
|
| 52 |
+
required_cols = ['voltage', 'frequency', 'load', 'solar_gen', 'wind_gen']
|
| 53 |
+
if not all(col in df.columns for col in required_cols):
|
| 54 |
+
st.error(f"CSV must contain columns: {required_cols}")
|
|
|
|
|
|
|
| 55 |
else:
|
| 56 |
+
st.success("✅ File uploaded and validated.")
|
| 57 |
+
st.write("Preview of uploaded data:")
|
| 58 |
+
st.dataframe(df.head())
|
| 59 |
|
| 60 |
+
model, scaler = load_model_and_scaler()
|
|
|
|
| 61 |
|
| 62 |
+
predictions = predict(df[required_cols], model, scaler)
|
| 63 |
+
df["Outage Probability"] = predictions
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
+
st.write("📊 Prediction Results:")
|
| 66 |
+
st.dataframe(df)
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
# Visualization
|
| 69 |
+
fig = px.line(df, y="Outage Probability", title="Line Outage Probability Over Time")
|
| 70 |
+
st.plotly_chart(fig)
|