Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import time
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
import joblib
|
| 6 |
+
import requests
|
| 7 |
+
import streamlit as st
|
| 8 |
+
from streamlit_autorefresh import st_autorefresh
|
| 9 |
+
|
| 10 |
+
# Auto-refresh every 5 seconds
|
| 11 |
+
st_autorefresh(interval=5000, key="refresh")
|
| 12 |
+
|
| 13 |
+
# Load model
|
| 14 |
+
@st.cache_resource
|
| 15 |
+
def load_model():
|
| 16 |
+
return joblib.load("rf_model.pkl")
|
| 17 |
+
|
| 18 |
+
model = load_model()
|
| 19 |
+
|
| 20 |
+
# Supabase config
|
| 21 |
+
SUPABASE_URL = os.environ["SUPABASE_URL"]
|
| 22 |
+
SUPABASE_KEY = os.environ["SUPABASE_KEY"]
|
| 23 |
+
TABLE = "smart_meter_readings_1year"
|
| 24 |
+
|
| 25 |
+
# Initialize session state
|
| 26 |
+
if "row_index" not in st.session_state:
|
| 27 |
+
st.session_state.row_index = 0
|
| 28 |
+
if "history" not in st.session_state:
|
| 29 |
+
st.session_state.history = pd.DataFrame()
|
| 30 |
+
|
| 31 |
+
# Fetch all data
|
| 32 |
+
@st.cache_data
|
| 33 |
+
def fetch_all_data():
|
| 34 |
+
url = f"{SUPABASE_URL}/rest/v1/{TABLE}?select=*&order=timestamp.asc"
|
| 35 |
+
headers = {
|
| 36 |
+
"apikey": SUPABASE_KEY,
|
| 37 |
+
"Authorization": f"Bearer {SUPABASE_KEY}"
|
| 38 |
+
}
|
| 39 |
+
r = requests.get(url, headers=headers)
|
| 40 |
+
if r.ok:
|
| 41 |
+
return pd.DataFrame(r.json())
|
| 42 |
+
else:
|
| 43 |
+
st.error(f"❌ Error fetching data: {r.status_code}")
|
| 44 |
+
return pd.DataFrame()
|
| 45 |
+
|
| 46 |
+
df_all = fetch_all_data()
|
| 47 |
+
|
| 48 |
+
# Debug sidebar
|
| 49 |
+
st.sidebar.title("🛠 Debug Info")
|
| 50 |
+
st.sidebar.write("Row index:", st.session_state.row_index)
|
| 51 |
+
st.sidebar.write("Total rows:", len(df_all))
|
| 52 |
+
if not df_all.empty and st.session_state.row_index < len(df_all):
|
| 53 |
+
st.sidebar.write("Next row:", df_all.iloc[st.session_state.row_index].to_dict())
|
| 54 |
+
|
| 55 |
+
# Get next row
|
| 56 |
+
def get_next_row():
|
| 57 |
+
if st.session_state.row_index < len(df_all):
|
| 58 |
+
row = df_all.iloc[[st.session_state.row_index]]
|
| 59 |
+
st.session_state.row_index += 1
|
| 60 |
+
return row
|
| 61 |
+
return pd.DataFrame()
|
| 62 |
+
|
| 63 |
+
# Feature engineering
|
| 64 |
+
def engineer(df):
|
| 65 |
+
# Handle timestamp
|
| 66 |
+
if pd.api.types.is_numeric_dtype(df["timestamp"]):
|
| 67 |
+
df["datetime"] = pd.to_datetime(df["timestamp"], unit="s")
|
| 68 |
+
else:
|
| 69 |
+
df["datetime"] = pd.to_datetime(df["timestamp"])
|
| 70 |
+
|
| 71 |
+
df["hour_of_day"] = df["datetime"].dt.hour
|
| 72 |
+
df["lag_30min"] = df["power_consumption_kwh"].shift(1)
|
| 73 |
+
df["lag_1h"] = df["power_consumption_kwh"].shift(2)
|
| 74 |
+
df["rolling_avg_1h"] = df["power_consumption_kwh"].rolling(2).mean()
|
| 75 |
+
df["rolling_avg_2h"] = df["power_consumption_kwh"].rolling(4).mean()
|
| 76 |
+
df["is_weekend"] = df["datetime"].dt.weekday >= 5
|
| 77 |
+
df["hour_sin"] = np.sin(2 * np.pi * df["hour_of_day"] / 24)
|
| 78 |
+
df["hour_cos"] = np.cos(2 * np.pi * df["hour_of_day"] / 24)
|
| 79 |
+
|
| 80 |
+
# One-hot encode property_type and region
|
| 81 |
+
df = pd.get_dummies(df, columns=["property_type", "region"], drop_first=False)
|
| 82 |
+
|
| 83 |
+
# Ensure all expected features exist
|
| 84 |
+
expected_features = [
|
| 85 |
+
'lag_30min', 'lag_1h',
|
| 86 |
+
'rolling_avg_1h', 'rolling_avg_2h',
|
| 87 |
+
'hour_of_day', 'is_weekend',
|
| 88 |
+
'hour_sin', 'hour_cos',
|
| 89 |
+
'temperature_c', 'ev_owner', 'solar_installed',
|
| 90 |
+
'property_type_commercial', 'property_type_residential',
|
| 91 |
+
'region_north', 'region_south', 'region_east', 'region_west'
|
| 92 |
+
]
|
| 93 |
+
|
| 94 |
+
for col in expected_features:
|
| 95 |
+
if col not in df.columns:
|
| 96 |
+
df[col] = 0
|
| 97 |
+
|
| 98 |
+
return df
|
| 99 |
+
|
| 100 |
+
# UI layout
|
| 101 |
+
st.title("⚡ Gridflux: Live Smart-Meter Forecast")
|
| 102 |
+
|
| 103 |
+
placeholder_chart = st.empty()
|
| 104 |
+
placeholder_metric = st.empty()
|
| 105 |
+
|
| 106 |
+
new_row = get_next_row()
|
| 107 |
+
|
| 108 |
+
if not new_row.empty:
|
| 109 |
+
st.session_state.history = pd.concat([st.session_state.history, new_row], ignore_index=True)
|
| 110 |
+
df_feat = engineer(st.session_state.history).dropna()
|
| 111 |
+
|
| 112 |
+
if not df_feat.empty:
|
| 113 |
+
latest_input = df_feat.iloc[[-1]][[
|
| 114 |
+
'lag_30min', 'lag_1h',
|
| 115 |
+
'rolling_avg_1h', 'rolling_avg_2h',
|
| 116 |
+
'hour_of_day', 'is_weekend',
|
| 117 |
+
'hour_sin', 'hour_cos',
|
| 118 |
+
'temperature_c', 'ev_owner', 'solar_installed',
|
| 119 |
+
'property_type_commercial', 'property_type_residential',
|
| 120 |
+
'region_north', 'region_south', 'region_east', 'region_west'
|
| 121 |
+
]]
|
| 122 |
+
|
| 123 |
+
prediction = model.predict(latest_input)[0]
|
| 124 |
+
|
| 125 |
+
# Show outputs
|
| 126 |
+
chart_df = st.session_state.history.copy()
|
| 127 |
+
chart_df["datetime"] = pd.to_datetime(chart_df["timestamp"])
|
| 128 |
+
chart_df.set_index("datetime", inplace=True)
|
| 129 |
+
|
| 130 |
+
placeholder_chart.line_chart(chart_df["power_consumption_kwh"])
|
| 131 |
+
placeholder_metric.metric("🔮 Predicted Power Usage (kWh)", f"{prediction:.3f}")
|
| 132 |
+
else:
|
| 133 |
+
st.success("✅ All data processed.")
|