Update app.py
Browse files
app.py
CHANGED
|
@@ -1,210 +1,432 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import plotly.express as px
|
| 6 |
import pandas as pd
|
| 7 |
-
import
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
-
|
| 17 |
-
flask_thread.start()
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
except Exception:
|
| 26 |
-
time.sleep(0.5)
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
lagging_pf,
|
| 41 |
-
leading_pf,
|
| 42 |
-
nsm,
|
| 43 |
-
week_status,
|
| 44 |
-
day_of_week,
|
| 45 |
-
load_type,
|
| 46 |
-
):
|
| 47 |
-
payload = {
|
| 48 |
-
'lagging_kvarh': lagging_kvarh,
|
| 49 |
-
'leading_kvarh': leading_kvarh,
|
| 50 |
-
'lagging_pf': lagging_pf,
|
| 51 |
-
'leading_pf': leading_pf,
|
| 52 |
-
'nsm': nsm,
|
| 53 |
-
'week_status': week_status,
|
| 54 |
-
'day_of_week': day_of_week,
|
| 55 |
-
'load_type': load_type,
|
| 56 |
-
}
|
| 57 |
-
|
| 58 |
-
try:
|
| 59 |
-
resp = requests.post('http://127.0.0.1:5000/predict', json=payload)
|
| 60 |
-
if resp.status_code == 200:
|
| 61 |
-
res = resp.json()
|
| 62 |
-
|
| 63 |
-
kwh_str = f"{res['predicted_usage_kwh']} kWh"
|
| 64 |
-
co2_str = f"{res['estimated_co2']} tCO2"
|
| 65 |
-
pf_str = res['power_factor_efficiency']
|
| 66 |
-
status_str = f"[{res['db_status']}] {res['mitigation_status']}"
|
| 67 |
-
|
| 68 |
-
# Fetch History Logs for Trend Chart
|
| 69 |
-
hist_resp = requests.get('http://127.0.0.1:5000/history')
|
| 70 |
-
if (
|
| 71 |
-
hist_resp.status_code == 200
|
| 72 |
-
and hist_resp.json().get('status') == 'success'
|
| 73 |
-
):
|
| 74 |
-
logs = hist_resp.json().get('data', [])
|
| 75 |
-
if logs:
|
| 76 |
-
df_logs = pd.DataFrame(logs)
|
| 77 |
-
fig = px.line(
|
| 78 |
-
df_logs,
|
| 79 |
-
x='id',
|
| 80 |
-
y='predicted_usage_kwh',
|
| 81 |
-
title='Historical Power Usage Trend (kWh)',
|
| 82 |
-
markers=True,
|
| 83 |
-
)
|
| 84 |
-
fig.update_layout(
|
| 85 |
-
template='plotly_dark', paper_bgcolor='#1f2937', plot_bgcolor='#111827'
|
| 86 |
-
)
|
| 87 |
-
else:
|
| 88 |
-
fig = px.line(title='No trend data recorded yet.')
|
| 89 |
-
else:
|
| 90 |
-
fig = px.line(title='Analytics service offline.')
|
| 91 |
-
|
| 92 |
-
return kwh_str, co2_str, pf_str, status_str, fig
|
| 93 |
-
|
| 94 |
-
return 'API Error', 'API Error', 'API Error', 'Failed to query server', px.line()
|
| 95 |
-
|
| 96 |
-
except Exception as err:
|
| 97 |
-
return 'Error', 'Error', 'Error', str(err), px.line()
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
# 4. Gradio Dashboard UI Construction
|
| 101 |
-
with gr.Blocks() as demo:
|
| 102 |
-
gr.Markdown(
|
| 103 |
-
'# ⚡ SteelPlant Analytics — Power & Carbon Mitigation Engine',
|
| 104 |
-
elem_classes=['main-title'],
|
| 105 |
-
)
|
| 106 |
-
gr.Markdown(
|
| 107 |
-
'Predict High-Voltage Energy Consumption, Monitor CO₂ Emissions & Identify'
|
| 108 |
-
' Power Grid Inefficiencies',
|
| 109 |
-
elem_classes=['sub-title'],
|
| 110 |
-
)
|
| 111 |
-
|
| 112 |
-
# --- TOP KPI METRIC CARDS ---
|
| 113 |
-
with gr.Row():
|
| 114 |
-
kpi_kwh = gr.Textbox(
|
| 115 |
-
label='Predicted Power Usage', value='-- kWh', interactive=False
|
| 116 |
)
|
| 117 |
-
|
| 118 |
-
|
|
|
|
| 119 |
)
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
)
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
value='Light_Load',
|
| 178 |
-
label='Plant Load Type',
|
| 179 |
-
)
|
| 180 |
-
|
| 181 |
-
btn_run = gr.Button('⚡ Run Mitigation Analytics', variant='primary')
|
| 182 |
-
|
| 183 |
-
# Right Analytics Charts Column
|
| 184 |
-
with gr.Column(scale=2):
|
| 185 |
-
gr.Markdown('### 📈 Power Demand Trend')
|
| 186 |
-
chart_plot = gr.Plot(label='Energy Demand Logs')
|
| 187 |
-
|
| 188 |
-
# Event Linkage
|
| 189 |
-
btn_run.click(
|
| 190 |
-
fn=run_analytics_pipeline,
|
| 191 |
-
inputs=[
|
| 192 |
-
lagging_kvarh,
|
| 193 |
-
leading_kvarh,
|
| 194 |
-
lagging_pf,
|
| 195 |
-
leading_pf,
|
| 196 |
-
nsm,
|
| 197 |
-
week_status,
|
| 198 |
-
day_of_week,
|
| 199 |
-
load_type,
|
| 200 |
-
],
|
| 201 |
-
outputs=[kpi_kwh, kpi_co2, kpi_pf, kpi_status, chart_plot],
|
| 202 |
-
)
|
| 203 |
-
|
| 204 |
-
if __name__ == '__main__':
|
| 205 |
-
demo.launch(
|
| 206 |
-
server_name='0.0.0.0',
|
| 207 |
-
server_port=7860,
|
| 208 |
-
theme=gr.themes.Soft(),
|
| 209 |
-
css=CUSTOM_CSS,
|
| 210 |
-
)
|
|
|
|
| 1 |
import os
|
| 2 |
+
import io
|
| 3 |
+
import datetime
|
| 4 |
+
import joblib
|
|
|
|
| 5 |
import pandas as pd
|
| 6 |
+
import numpy as np
|
| 7 |
+
import mysql.connector
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from reportlab.lib.pagesizes import letter
|
| 10 |
+
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
|
| 11 |
+
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 12 |
+
from reportlab.lib import colors
|
| 13 |
|
| 14 |
+
# ---------------------------------------------------------------------------
|
| 15 |
+
# 1. DATABASE CONFIGURATION (FreeDatabase.com / MySQL)
|
| 16 |
+
# ---------------------------------------------------------------------------
|
| 17 |
+
DB_HOST = os.getenv("MYSQL_HOST", "sql6.freedatabase.com")
|
| 18 |
+
DB_USER = os.getenv("MYSQL_USER", "your_username")
|
| 19 |
+
DB_PASS = os.getenv("MYSQL_PASSWORD", "your_password")
|
| 20 |
+
DB_NAME = os.getenv("MYSQL_DB", "your_dbname")
|
| 21 |
+
DB_PORT = int(os.getenv("MYSQL_PORT", 3306))
|
| 22 |
|
| 23 |
+
def get_db_connection():
|
| 24 |
+
try:
|
| 25 |
+
conn = mysql.connector.connect(
|
| 26 |
+
host=DB_HOST,
|
| 27 |
+
user=DB_USER,
|
| 28 |
+
password=DB_PASS,
|
| 29 |
+
database=DB_NAME,
|
| 30 |
+
port=DB_PORT,
|
| 31 |
+
connect_timeout=5
|
| 32 |
+
)
|
| 33 |
+
return conn
|
| 34 |
+
except Exception as e:
|
| 35 |
+
print(f"[DB Warning] Could not connect to MySQL database: {e}")
|
| 36 |
+
return None
|
| 37 |
|
| 38 |
+
def init_db():
|
| 39 |
+
conn = get_db_connection()
|
| 40 |
+
if conn:
|
| 41 |
+
try:
|
| 42 |
+
cursor = conn.cursor()
|
| 43 |
+
cursor.execute("""
|
| 44 |
+
CREATE TABLE IF NOT EXISTS energy_predictions (
|
| 45 |
+
id INT AUTO_INCREMENT PRIMARY KEY,
|
| 46 |
+
prediction_type VARCHAR(20),
|
| 47 |
+
avg_usage_kwh FLOAT,
|
| 48 |
+
total_co2_tonnes FLOAT,
|
| 49 |
+
timestamp DATETIME
|
| 50 |
+
)
|
| 51 |
+
""")
|
| 52 |
+
conn.commit()
|
| 53 |
+
cursor.close()
|
| 54 |
+
conn.close()
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"[DB Init Error] {e}")
|
| 57 |
|
| 58 |
+
init_db()
|
|
|
|
| 59 |
|
| 60 |
+
# ---------------------------------------------------------------------------
|
| 61 |
+
# 2. MODEL & ARTIFACT LOADING
|
| 62 |
+
# ---------------------------------------------------------------------------
|
| 63 |
+
MODEL_PATH = 'steel_model.joblib'
|
| 64 |
+
SCALER_PATH = 'scaler.joblib'
|
| 65 |
+
COLUMNS_PATH = 'model_columns.joblib'
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
# Fallback in-memory models if files are absent
|
| 68 |
+
if os.path.exists(MODEL_PATH) and os.path.exists(SCALER_PATH) and os.path.exists(COLUMNS_PATH):
|
| 69 |
+
model = joblib.load(MODEL_PATH)
|
| 70 |
+
scaler = joblib.load(SCALER_PATH)
|
| 71 |
+
feature_columns = joblib.load(COLUMNS_PATH)
|
| 72 |
+
else:
|
| 73 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 74 |
+
from sklearn.preprocessing import StandardScaler
|
| 75 |
+
|
| 76 |
+
feature_columns = [
|
| 77 |
+
'Lagging_Current_Reactive_Power_kVarh', 'Leading_Current_Reactive_Power_kVarh',
|
| 78 |
+
'Lagging_Current_Power_Factor', 'Leading_Current_Power_Factor', 'NSM',
|
| 79 |
+
'Hour', 'Month', 'Reactive_Power_Ratio', 'Power_Factor_Ratio',
|
| 80 |
+
'WeekStatus_Weekend', 'Day_of_week_Monday', 'Day_of_week_Saturday',
|
| 81 |
+
'Day_of_week_Sunday', 'Day_of_week_Thursday', 'Day_of_week_Tuesday',
|
| 82 |
+
'Day_of_week_Wednesday', 'Load_Type_Maximum_Load', 'Load_Type_Medium_Load'
|
| 83 |
+
]
|
| 84 |
+
scaler = StandardScaler()
|
| 85 |
+
scaler.fit(np.zeros((10, len(feature_columns))))
|
| 86 |
+
model = RandomForestRegressor(n_estimators=10, max_depth=5, random_state=42)
|
| 87 |
+
model.fit(np.zeros((10, len(feature_columns))), np.zeros(10))
|
| 88 |
|
| 89 |
+
# ---------------------------------------------------------------------------
|
| 90 |
+
# 3. FEATURE ENGINEERING & PREDICTION PIPELINE
|
| 91 |
+
# ---------------------------------------------------------------------------
|
| 92 |
+
def preprocess_and_predict(df_raw):
|
| 93 |
+
df = df_raw.copy()
|
| 94 |
+
df.columns = (
|
| 95 |
+
df.columns.str.strip()
|
| 96 |
+
.str.replace(' ', '_')
|
| 97 |
+
.str.replace('(', '', regex=False)
|
| 98 |
+
.str.replace(')', '', regex=False)
|
| 99 |
+
.str.replace('.', '_', regex=False)
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if 'date' in df.columns:
|
| 103 |
+
df['date'] = pd.to_datetime(df['date'], format='%d/%m/%Y %H:%M', errors='coerce')
|
| 104 |
+
df['Hour'] = df['date'].dt.hour.fillna(12).astype(int)
|
| 105 |
+
df['Month'] = df['date'].dt.month.fillna(1).astype(int)
|
| 106 |
+
else:
|
| 107 |
+
df['Hour'] = 12
|
| 108 |
+
df['Month'] = 1
|
| 109 |
|
| 110 |
+
eps = 1e-5
|
| 111 |
+
df['Reactive_Power_Ratio'] = (
|
| 112 |
+
df['Lagging_Current_Reactive_Power_kVarh'] /
|
| 113 |
+
(df['Leading_Current_Reactive_Power_kVarh'] + eps)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
)
|
| 115 |
+
df['Power_Factor_Ratio'] = (
|
| 116 |
+
df['Lagging_Current_Power_Factor'] /
|
| 117 |
+
(df['Leading_Current_Power_Factor'] + eps)
|
| 118 |
)
|
| 119 |
+
|
| 120 |
+
df_encoded = pd.get_dummies(df, drop_first=True)
|
| 121 |
+
|
| 122 |
+
# Reindex columns to match model training setup
|
| 123 |
+
X_processed = pd.DataFrame(0, index=df.index, columns=feature_columns)
|
| 124 |
+
for col in feature_columns:
|
| 125 |
+
if col in df_encoded.columns:
|
| 126 |
+
X_processed[col] = df_encoded[col]
|
| 127 |
+
|
| 128 |
+
X_scaled = scaler.transform(X_processed)
|
| 129 |
+
predictions = model.predict(X_scaled)
|
| 130 |
+
|
| 131 |
+
df['Predicted_Usage_kWh'] = np.round(predictions, 4)
|
| 132 |
+
df['Estimated_CO2_Tonnes'] = np.round(predictions * 0.00042, 6)
|
| 133 |
+
|
| 134 |
+
return df
|
| 135 |
+
|
| 136 |
+
# ---------------------------------------------------------------------------
|
| 137 |
+
# 4. PDF GENERATION ENGINE
|
| 138 |
+
# ---------------------------------------------------------------------------
|
| 139 |
+
def generate_pdf_report(df_results, summary_stats):
|
| 140 |
+
pdf_buffer = io.BytesIO()
|
| 141 |
+
doc = SimpleDocTemplate(pdf_buffer, pagesize=letter, rightMargin=36, leftMargin=36, topMargin=36, bottomMargin=36)
|
| 142 |
+
styles = getSampleStyleSheet()
|
| 143 |
+
|
| 144 |
+
title_style = ParagraphStyle(
|
| 145 |
+
'DocTitle',
|
| 146 |
+
parent=styles['Heading1'],
|
| 147 |
+
fontName='Helvetica-Bold',
|
| 148 |
+
fontSize=20,
|
| 149 |
+
textColor=colors.HexColor('#0f172a'),
|
| 150 |
+
spaceAfter=12
|
| 151 |
)
|
| 152 |
+
|
| 153 |
+
subtitle_style = ParagraphStyle(
|
| 154 |
+
'DocSubTitle',
|
| 155 |
+
parent=styles['Normal'],
|
| 156 |
+
fontName='Helvetica',
|
| 157 |
+
fontSize=10,
|
| 158 |
+
textColor=colors.HexColor('#64748b'),
|
| 159 |
+
spaceAfter=20
|
| 160 |
)
|
| 161 |
+
|
| 162 |
+
elements = []
|
| 163 |
+
elements.append(Paragraph("Steel Plant Energy & CO2 Audit Report", title_style))
|
| 164 |
+
elements.append(Paragraph(f"Generated on: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | Hugging Face Spaces Engine", subtitle_style))
|
| 165 |
+
|
| 166 |
+
# Summary Table
|
| 167 |
+
summary_data = [
|
| 168 |
+
["Metric Description", "Value"],
|
| 169 |
+
["Total Processed Records", f"{summary_stats['total_records']}"],
|
| 170 |
+
["Mean Electricity Demand (kWh)", f"{summary_stats['mean_kwh']:.2f} kWh"],
|
| 171 |
+
["Max Electricity Demand (kWh)", f"{summary_stats['max_kwh']:.2f} kWh"],
|
| 172 |
+
["Total Estimated CO2 Footprint", f"{summary_stats['total_co2']:.4f} Metric Tonnes"],
|
| 173 |
+
["Mitigated Potential CO2 Saved (10% Peak Reduction)", f"{summary_stats['mitigated_co2']:.4f} Metric Tonnes"]
|
| 174 |
+
]
|
| 175 |
+
|
| 176 |
+
st = Table(summary_data, colWidths=[300, 220])
|
| 177 |
+
st.setStyle(TableStyle([
|
| 178 |
+
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#1e293b')),
|
| 179 |
+
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
|
| 180 |
+
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
|
| 181 |
+
('FONTSIZE', (0, 0), (-1, -1), 10),
|
| 182 |
+
('BOTTOMPADDING', (0, 0), (-1, -1), 8),
|
| 183 |
+
('TOPPADDING', (0, 0), (-1, -1), 8),
|
| 184 |
+
('BACKGROUND', (0, 1), (-1, -1), colors.HexColor('#f8fafc')),
|
| 185 |
+
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#cbd5e1')),
|
| 186 |
+
]))
|
| 187 |
+
|
| 188 |
+
elements.append(st)
|
| 189 |
+
elements.append(Spacer(1, 20))
|
| 190 |
+
|
| 191 |
+
# Sample Output Table
|
| 192 |
+
elements.append(Paragraph("Sample Predictions Preview (First 10 Rows)", styles['Heading2']))
|
| 193 |
+
preview_df = df_results[['Predicted_Usage_kWh', 'Estimated_CO2_Tonnes']].head(10).reset_index()
|
| 194 |
+
|
| 195 |
+
preview_data = [["Row ID", "Predicted Usage (kWh)", "Estimated CO2 (Tonnes)"]]
|
| 196 |
+
for _, row in preview_df.iterrows():
|
| 197 |
+
preview_data.append([str(int(row['index'] + 1)), f"{row['Predicted_Usage_kWh']:.2f}", f"{row['Estimated_CO2_Tonnes']:.6f}"])
|
| 198 |
+
|
| 199 |
+
pt = Table(preview_data, colWidths=[100, 210, 210])
|
| 200 |
+
pt.setStyle(TableStyle([
|
| 201 |
+
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#0284c7')),
|
| 202 |
+
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
|
| 203 |
+
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
|
| 204 |
+
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#e2e8f0')),
|
| 205 |
+
('TOPPADDING', (0, 0), (-1, -1), 5),
|
| 206 |
+
('BOTTOMPADDING', (0, 0), (-1, -1), 5),
|
| 207 |
+
]))
|
| 208 |
+
|
| 209 |
+
elements.append(pt)
|
| 210 |
+
doc.build(elements)
|
| 211 |
+
|
| 212 |
+
pdf_buffer.seek(0)
|
| 213 |
+
pdf_path = "/tmp/energy_prediction_report.pdf"
|
| 214 |
+
with open(pdf_path, "wb") as f:
|
| 215 |
+
f.write(pdf_buffer.read())
|
| 216 |
+
|
| 217 |
+
return pdf_path
|
| 218 |
|
| 219 |
+
# ---------------------------------------------------------------------------
|
| 220 |
+
# 5. GRADIO HANDLERS
|
| 221 |
+
# ---------------------------------------------------------------------------
|
| 222 |
+
def handle_single_prediction(lag_kvarh, lead_kvarh, lag_pf, lead_pf, nsm, hour, month, day_of_week, load_type):
|
| 223 |
+
data = {
|
| 224 |
+
'Lagging_Current_Reactive_Power_kVarh': [lag_kvarh],
|
| 225 |
+
'Leading_Current_Reactive_Power_kVarh': [lead_kvarh],
|
| 226 |
+
'Lagging_Current_Power_Factor': [lag_pf],
|
| 227 |
+
'Leading_Current_Power_Factor': [lead_pf],
|
| 228 |
+
'NSM': [nsm],
|
| 229 |
+
'Hour': [hour],
|
| 230 |
+
'Month': [month],
|
| 231 |
+
'Day_of_week': [day_of_week],
|
| 232 |
+
'Load_Type': [load_type],
|
| 233 |
+
'WeekStatus': ['Weekend' if day_of_week in ['Saturday', 'Sunday'] else 'Weekday']
|
| 234 |
+
}
|
| 235 |
+
df_single = pd.DataFrame(data)
|
| 236 |
+
res = preprocess_and_predict(df_single)
|
| 237 |
+
|
| 238 |
+
kwh = float(res['Predicted_Usage_kWh'].iloc[0])
|
| 239 |
+
co2 = float(res['Estimated_CO2_Tonnes'].iloc[0])
|
| 240 |
+
|
| 241 |
+
# Save to FreeDatabase MySQL async/safe
|
| 242 |
+
conn = get_db_connection()
|
| 243 |
+
if conn:
|
| 244 |
+
try:
|
| 245 |
+
cursor = conn.cursor()
|
| 246 |
+
cursor.execute(
|
| 247 |
+
"INSERT INTO energy_predictions (prediction_type, avg_usage_kwh, total_co2_tonnes, timestamp) VALUES (%s, %s, %s, %s)",
|
| 248 |
+
('SINGLE', kwh, co2, datetime.datetime.now())
|
| 249 |
+
)
|
| 250 |
+
conn.commit()
|
| 251 |
+
cursor.close()
|
| 252 |
+
conn.close()
|
| 253 |
+
except Exception as e:
|
| 254 |
+
print(f"[DB Write Error] {e}")
|
| 255 |
+
|
| 256 |
+
return f"{kwh:.2f} kWh", f"{co2:.6f} Metric Tonnes"
|
| 257 |
+
|
| 258 |
+
def handle_csv_upload(file):
|
| 259 |
+
if file is None:
|
| 260 |
+
return None, "Please upload a valid CSV file.", None
|
| 261 |
+
|
| 262 |
+
df_raw = pd.read_csv(file.name)
|
| 263 |
+
df_results = preprocess_and_predict(df_raw)
|
| 264 |
+
|
| 265 |
+
total_records = len(df_results)
|
| 266 |
+
mean_kwh = df_results['Predicted_Usage_kWh'].mean()
|
| 267 |
+
max_kwh = df_results['Predicted_Usage_kWh'].max()
|
| 268 |
+
total_co2 = df_results['Estimated_CO2_Tonnes'].sum()
|
| 269 |
+
|
| 270 |
+
# Simulate mitigation (10% drop on peak usage > mean)
|
| 271 |
+
mitigated_kwh = df_results['Predicted_Usage_kWh'].copy()
|
| 272 |
+
mitigated_kwh[mitigated_kwh > mean_kwh] *= 0.90
|
| 273 |
+
mitigated_co2 = (df_results['Estimated_CO2_Tonnes'].sum() - (mitigated_kwh * 0.00042).sum())
|
| 274 |
+
|
| 275 |
+
summary_stats = {
|
| 276 |
+
'total_records': total_records,
|
| 277 |
+
'mean_kwh': mean_kwh,
|
| 278 |
+
'max_kwh': max_kwh,
|
| 279 |
+
'total_co2': total_co2,
|
| 280 |
+
'mitigated_co2': mitigated_co2
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
pdf_path = generate_pdf_report(df_results, summary_stats)
|
| 284 |
+
|
| 285 |
+
summary_text = f"""
|
| 286 |
+
### 📊 Analysis Summary
|
| 287 |
+
* **Total Processed Records:** {total_records}
|
| 288 |
+
* **Average Predicted Demand:** {mean_kwh:.2f} kWh
|
| 289 |
+
* **Peak Demand Recorded:** {max_kwh:.2f} kWh
|
| 290 |
+
* **Total Estimated Carbon Footprint:** {total_co2:.4f} Metric Tonnes
|
| 291 |
+
* **Potential CO2 Saved (via Peak Factor Mitigation):** {mitigated_co2:.4f} Metric Tonnes
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
# Save batch summary to MySQL
|
| 295 |
+
conn = get_db_connection()
|
| 296 |
+
if conn:
|
| 297 |
+
try:
|
| 298 |
+
cursor = conn.cursor()
|
| 299 |
+
cursor.execute(
|
| 300 |
+
"INSERT INTO energy_predictions (prediction_type, avg_usage_kwh, total_co2_tonnes, timestamp) VALUES (%s, %s, %s, %s)",
|
| 301 |
+
('BATCH_CSV', mean_kwh, total_co2, datetime.datetime.now())
|
| 302 |
+
)
|
| 303 |
+
conn.commit()
|
| 304 |
+
cursor.close()
|
| 305 |
+
conn.close()
|
| 306 |
+
except Exception as e:
|
| 307 |
+
print(f"[DB Write Error] {e}")
|
| 308 |
+
|
| 309 |
+
return df_results, summary_text, pdf_path
|
| 310 |
+
|
| 311 |
+
# ---------------------------------------------------------------------------
|
| 312 |
+
# 6. SLEEK & GLOSSY GRADIO UI (WITH FUNCTIONAL SIDEBAR PANEL)
|
| 313 |
+
# ---------------------------------------------------------------------------
|
| 314 |
+
custom_css = """
|
| 315 |
+
/* Sleek Glossy Modern Interface Styling */
|
| 316 |
+
body, .gradio-container {
|
| 317 |
+
background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%) !important;
|
| 318 |
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
|
| 319 |
+
color: #f8fafc !important;
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
/* Glassmorphism Cards */
|
| 323 |
+
.glass-panel {
|
| 324 |
+
background: rgba(30, 41, 59, 0.7) !important;
|
| 325 |
+
backdrop-filter: blur(12px) !important;
|
| 326 |
+
-webkit-backdrop-filter: blur(12px) !important;
|
| 327 |
+
border: 1px solid rgba(255, 255, 255, 0.1) !important;
|
| 328 |
+
border-radius: 16px !important;
|
| 329 |
+
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 8px 10px -6px rgba(0, 0, 0, 0.5) !important;
|
| 330 |
+
padding: 20px !important;
|
| 331 |
+
margin-bottom: 20px !important;
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
/* Glossy Sidebar */
|
| 335 |
+
.sidebar-panel {
|
| 336 |
+
background: rgba(15, 23, 42, 0.85) !important;
|
| 337 |
+
border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
|
| 338 |
+
padding: 24px !important;
|
| 339 |
+
border-radius: 16px !important;
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
/* Custom Buttons */
|
| 343 |
+
.btn-primary {
|
| 344 |
+
background: linear-gradient(90deg, #0284c7 0%, #0369a1 100%) !important;
|
| 345 |
+
border: none !important;
|
| 346 |
+
color: #ffffff !important;
|
| 347 |
+
font-weight: 600 !important;
|
| 348 |
+
border-radius: 10px !important;
|
| 349 |
+
box-shadow: 0 4px 14px 0 rgba(2, 132, 199, 0.39) !important;
|
| 350 |
+
transition: all 0.3s ease !important;
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
.btn-primary:hover {
|
| 354 |
+
transform: translateY(-2px) !important;
|
| 355 |
+
box-shadow: 0 6px 20px 0 rgba(2, 132, 199, 0.5) !important;
|
| 356 |
+
}
|
| 357 |
+
"""
|
| 358 |
+
|
| 359 |
+
with gr.Blocks(css=custom_css, title="Steel Industry Energy Predictor") as demo:
|
| 360 |
+
gr.Markdown(
|
| 361 |
+
"""
|
| 362 |
+
# ⚡ Steel Industry Power Consumption & Carbon Footprint Portal
|
| 363 |
+
### *Sleek AI-Powered Energy Demand & Environmental Mitigation Analytics*
|
| 364 |
+
"""
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
with gr.Row():
|
| 368 |
+
# --- FUNCTIONAL SIDEBAR PANEL ---
|
| 369 |
+
with gr.Column(scale=1, elem_classes=["sidebar-panel"]):
|
| 370 |
+
gr.Markdown("### ⚙️ Input Control Sidebar")
|
| 371 |
+
gr.Markdown("Configure manual parameters or run batch processes directly.")
|
| 372 |
+
|
| 373 |
+
with gr.Accordion("Single Inspection Parameters", open=True):
|
| 374 |
+
lag_kvarh = gr.Number(label="Lagging Reactive Power (kVarh)", value=12.5)
|
| 375 |
+
lead_kvarh = gr.Number(label="Leading Reactive Power (kVarh)", value=2.1)
|
| 376 |
+
lag_pf = gr.Slider(minimum=0, maximum=100, label="Lagging Power Factor (%)", value=85.0)
|
| 377 |
+
lead_pf = gr.Slider(minimum=0, maximum=100, label="Leading Power Factor (%)", value=95.0)
|
| 378 |
+
nsm = gr.Number(label="Number of Seconds from Midnight (NSM)", value=36000)
|
| 379 |
+
hour = gr.Slider(minimum=0, maximum=23, step=1, label="Hour of Day", value=10)
|
| 380 |
+
month = gr.Slider(minimum=1, maximum=12, step=1, label="Month of Year", value=6)
|
| 381 |
+
day_of_week = gr.Dropdown(
|
| 382 |
+
choices=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
|
| 383 |
+
value='Monday',
|
| 384 |
+
label="Day of Week"
|
| 385 |
+
)
|
| 386 |
+
load_type = gr.Dropdown(
|
| 387 |
+
choices=['Light_Load', 'Medium_Load', 'Maximum_Load'],
|
| 388 |
+
value='Medium_Load',
|
| 389 |
+
label="Load Type Category"
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
predict_btn = gr.Button("🚀 Predict Single Record", elem_classes=["btn-primary"])
|
| 393 |
+
|
| 394 |
+
# --- MAIN WORKFLOW PANEL ---
|
| 395 |
+
with gr.Column(scale=3):
|
| 396 |
+
with gr.Tabs():
|
| 397 |
+
# TAB 1: CSV UPLOAD & PDF DOWNLOAD WORKFLOW
|
| 398 |
+
with gr.TabItem("📂 Batch CSV Upload & PDF Export"):
|
| 399 |
+
with gr.Group(elem_classes=["glass-panel"]):
|
| 400 |
+
gr.Markdown("### Upload Steel Industry Data CSV")
|
| 401 |
+
file_input = gr.File(label="Upload CSV File (`Steel_industry_data.csv`)", file_types=[".csv"])
|
| 402 |
+
process_csv_btn = gr.Button("⚡ Analyze CSV Data & Generate Report", elem_classes=["btn-primary"])
|
| 403 |
+
|
| 404 |
+
with gr.Row():
|
| 405 |
+
with gr.Column(scale=2):
|
| 406 |
+
output_dataframe = gr.Dataframe(label="Predictions Table Preview", interactive=False)
|
| 407 |
+
with gr.Column(scale=1):
|
| 408 |
+
summary_output = gr.Markdown(value="*Upload a CSV to view analysis summary.*")
|
| 409 |
+
pdf_download = gr.File(label="📄 Download PDF Audit Report")
|
| 410 |
+
|
| 411 |
+
# TAB 2: SINGLE PREDICTION RESULTS
|
| 412 |
+
with gr.TabItem("🎯 Single Record Result"):
|
| 413 |
+
with gr.Group(elem_classes=["glass-panel"]):
|
| 414 |
+
gr.Markdown("### Single Inspection Prediction Result")
|
| 415 |
+
out_kwh = gr.Textbox(label="Predicted Energy Consumption (Usage_kWh)", interactive=False)
|
| 416 |
+
out_co2 = gr.Textbox(label="Estimated Carbon Emissions (Tonnes CO2)", interactive=False)
|
| 417 |
+
|
| 418 |
+
# Event Bindings
|
| 419 |
+
predict_btn.click(
|
| 420 |
+
fn=handle_single_prediction,
|
| 421 |
+
inputs=[lag_kvarh, lead_kvarh, lag_pf, lead_pf, nsm, hour, month, day_of_week, load_type],
|
| 422 |
+
outputs=[out_kwh, out_co2]
|
| 423 |
+
)
|
| 424 |
+
|
| 425 |
+
process_csv_btn.click(
|
| 426 |
+
fn=handle_csv_upload,
|
| 427 |
+
inputs=[file_input],
|
| 428 |
+
outputs=[output_dataframe, summary_output, pdf_download]
|
| 429 |
+
)
|
| 430 |
|
| 431 |
+
if __name__ == "__main__":
|
| 432 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|