hareshchander commited on
Commit
fc54f3c
·
verified ·
1 Parent(s): ed8dc58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -94
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
- from app_backend import fetch_weather, generate_synthetic_data, optimize_load
 
8
 
9
- # Constants
10
- API_KEY = "84e26811a314599e940f343b4d5894a7"
11
- DEFAULT_LOCATION = "New York"
 
 
 
 
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.layers(x)
27
 
28
- # Load scaler and model once
29
  @st.cache_resource
30
  def load_model_and_scaler():
31
- scaler = joblib.load("scaler.pkl")
32
- model = GridModel()
33
- model.load_state_dict(torch.load("model.pth", map_location=torch.device('cpu')))
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
- # Main dashboard title
51
- st.title("Real-Time Smart Grid Dashboard")
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
- required_columns = ["timestamp", "voltage", "frequency", "load", "solar_gen", "wind_gen", "grid_health"]
64
- if all(col in data.columns for col in required_columns):
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
- fig_renew = px.bar(
71
- data,
72
- x="timestamp",
73
- y=["solar_gen", "wind_gen"],
74
- title="Renewable Energy Contributions",
75
- labels={"value": "Power (kW)", "variable": "Energy Source"}
76
- )
77
- st.plotly_chart(fig_renew)
78
 
79
- st.subheader("Grid Health Overview")
80
- grid_health_counts = data["grid_health"].value_counts()
81
- st.bar_chart(grid_health_counts)
82
 
83
- # Prepare features for model prediction
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
- # Run model prediction
89
- with torch.no_grad():
90
- outputs = model(inputs).numpy().flatten()
91
 
92
- # Compute average output as stability metric
93
- avg_output = outputs.mean()
94
- if avg_output < 0.4:
95
- status = "Unstable"
96
- elif avg_output < 0.7:
97
- status = "Warning"
98
  else:
99
- status = "Stable"
 
 
100
 
101
- st.subheader("Grid Stability Prediction")
102
- st.write(f"Predicted Grid Stability Status: **{status}** (Confidence: {avg_output:.2f})")
103
 
104
- # Optimization recommendations based on last timestamp
105
- current_demand = data["load"].iloc[-1]
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
- st.subheader("Recommendations")
111
- st.write(f"Current Load Demand: {current_demand} kWh")
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
- else:
117
- st.error(f"The uploaded data is missing one or more required columns: {required_columns}")
 
 
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)