Update app.py
Browse files
app.py
CHANGED
|
@@ -6,13 +6,16 @@ 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 (
|
| 16 |
# ---------------------------------------------------------------------------
|
| 17 |
DB_HOST = os.getenv("MYSQL_HOST", "sql6.freedatabase.com")
|
| 18 |
DB_USER = os.getenv("MYSQL_USER", "your_username")
|
|
@@ -28,11 +31,10 @@ def get_db_connection():
|
|
| 28 |
password=DB_PASS,
|
| 29 |
database=DB_NAME,
|
| 30 |
port=DB_PORT,
|
| 31 |
-
connect_timeout=
|
| 32 |
)
|
| 33 |
return conn
|
| 34 |
-
except Exception
|
| 35 |
-
print(f"[DB Warning] Could not connect to MySQL database: {e}")
|
| 36 |
return None
|
| 37 |
|
| 38 |
def init_db():
|
|
@@ -53,44 +55,28 @@ def init_db():
|
|
| 53 |
cursor.close()
|
| 54 |
conn.close()
|
| 55 |
except Exception as e:
|
| 56 |
-
print(f"[DB
|
| 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 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 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 |
-
|
| 91 |
-
# ---------------------------------------------------------------------------
|
| 92 |
-
def preprocess_and_predict(df_raw):
|
| 93 |
-
df = df_raw.copy()
|
| 94 |
df.columns = (
|
| 95 |
df.columns.str.strip()
|
| 96 |
.str.replace(' ', '_')
|
|
@@ -98,14 +84,100 @@ def preprocess_and_predict(df_raw):
|
|
| 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 |
-
|
| 108 |
-
|
|
|
|
|
|
|
| 109 |
|
| 110 |
eps = 1e-5
|
| 111 |
df['Reactive_Power_Ratio'] = (
|
|
@@ -117,9 +189,14 @@ def preprocess_and_predict(df_raw):
|
|
| 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:
|
|
@@ -145,7 +222,7 @@ def generate_pdf_report(df_results, summary_stats):
|
|
| 145 |
'DocTitle',
|
| 146 |
parent=styles['Heading1'],
|
| 147 |
fontName='Helvetica-Bold',
|
| 148 |
-
fontSize=
|
| 149 |
textColor=colors.HexColor('#0f172a'),
|
| 150 |
spaceAfter=12
|
| 151 |
)
|
|
@@ -156,39 +233,36 @@ def generate_pdf_report(df_results, summary_stats):
|
|
| 156 |
fontName='Helvetica',
|
| 157 |
fontSize=10,
|
| 158 |
textColor=colors.HexColor('#64748b'),
|
| 159 |
-
spaceAfter=
|
| 160 |
)
|
| 161 |
|
| 162 |
-
elements = [
|
| 163 |
-
|
| 164 |
-
|
|
|
|
| 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
|
| 174 |
]
|
| 175 |
|
| 176 |
-
st = Table(summary_data, colWidths=[
|
| 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,
|
| 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 |
|
|
@@ -196,7 +270,7 @@ def generate_pdf_report(df_results, summary_stats):
|
|
| 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=[
|
| 200 |
pt.setStyle(TableStyle([
|
| 201 |
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#0284c7')),
|
| 202 |
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
|
|
@@ -229,8 +303,7 @@ def handle_single_prediction(lag_kvarh, lead_kvarh, lag_pf, lead_pf, nsm, hour,
|
|
| 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)
|
|
@@ -238,7 +311,7 @@ def handle_single_prediction(lag_kvarh, lead_kvarh, lag_pf, lead_pf, nsm, hour,
|
|
| 238 |
kwh = float(res['Predicted_Usage_kWh'].iloc[0])
|
| 239 |
co2 = float(res['Estimated_CO2_Tonnes'].iloc[0])
|
| 240 |
|
| 241 |
-
#
|
| 242 |
conn = get_db_connection()
|
| 243 |
if conn:
|
| 244 |
try:
|
|
@@ -250,8 +323,8 @@ def handle_single_prediction(lag_kvarh, lead_kvarh, lag_pf, lead_pf, nsm, hour,
|
|
| 250 |
conn.commit()
|
| 251 |
cursor.close()
|
| 252 |
conn.close()
|
| 253 |
-
except Exception
|
| 254 |
-
|
| 255 |
|
| 256 |
return f"{kwh:.2f} kWh", f"{co2:.6f} Metric Tonnes"
|
| 257 |
|
|
@@ -263,14 +336,22 @@ def handle_csv_upload(file):
|
|
| 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 |
-
#
|
| 271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
mitigated_kwh[mitigated_kwh > mean_kwh] *= 0.90
|
| 273 |
-
mitigated_co2 = (
|
| 274 |
|
| 275 |
summary_stats = {
|
| 276 |
'total_records': total_records,
|
|
@@ -284,54 +365,34 @@ def handle_csv_upload(file):
|
|
| 284 |
|
| 285 |
summary_text = f"""
|
| 286 |
### 📊 Analysis Summary
|
| 287 |
-
* **Total Processed Records:** {total_records}
|
| 288 |
-
* **Average
|
| 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
|
| 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;
|
|
@@ -339,7 +400,6 @@ body, .gradio-container {
|
|
| 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;
|
|
@@ -347,12 +407,6 @@ body, .gradio-container {
|
|
| 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 |
|
|
@@ -365,7 +419,7 @@ with gr.Blocks(css=custom_css, title="Steel Industry Energy Predictor") as demo:
|
|
| 365 |
)
|
| 366 |
|
| 367 |
with gr.Row():
|
| 368 |
-
#
|
| 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.")
|
|
@@ -391,10 +445,10 @@ with gr.Blocks(css=custom_css, title="Steel Industry Energy Predictor") as demo:
|
|
| 391 |
|
| 392 |
predict_btn = gr.Button("🚀 Predict Single Record", elem_classes=["btn-primary"])
|
| 393 |
|
| 394 |
-
#
|
| 395 |
with gr.Column(scale=3):
|
| 396 |
with gr.Tabs():
|
| 397 |
-
# TAB 1: CSV UPLOAD &
|
| 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")
|
|
@@ -408,20 +462,40 @@ with gr.Blocks(css=custom_css, title="Steel Industry Energy Predictor") as demo:
|
|
| 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
|
| 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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 419 |
predict_btn.click(
|
| 420 |
fn=handle_single_prediction,
|
| 421 |
-
inputs=
|
| 422 |
-
outputs=
|
| 423 |
)
|
| 424 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
process_csv_btn.click(
|
| 426 |
fn=handle_csv_upload,
|
| 427 |
inputs=[file_input],
|
|
|
|
| 6 |
import numpy as np
|
| 7 |
import mysql.connector
|
| 8 |
import gradio as gr
|
| 9 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 10 |
+
from sklearn.preprocessing import StandardScaler
|
| 11 |
+
|
| 12 |
from reportlab.lib.pagesizes import letter
|
| 13 |
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
|
| 14 |
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 15 |
from reportlab.lib import colors
|
| 16 |
|
| 17 |
# ---------------------------------------------------------------------------
|
| 18 |
+
# 1. DATABASE CONFIGURATION (Safe MySQL / FreeDatabase Connector)
|
| 19 |
# ---------------------------------------------------------------------------
|
| 20 |
DB_HOST = os.getenv("MYSQL_HOST", "sql6.freedatabase.com")
|
| 21 |
DB_USER = os.getenv("MYSQL_USER", "your_username")
|
|
|
|
| 31 |
password=DB_PASS,
|
| 32 |
database=DB_NAME,
|
| 33 |
port=DB_PORT,
|
| 34 |
+
connect_timeout=3
|
| 35 |
)
|
| 36 |
return conn
|
| 37 |
+
except Exception:
|
|
|
|
| 38 |
return None
|
| 39 |
|
| 40 |
def init_db():
|
|
|
|
| 55 |
cursor.close()
|
| 56 |
conn.close()
|
| 57 |
except Exception as e:
|
| 58 |
+
print(f"[DB Warning] {e}")
|
| 59 |
|
| 60 |
init_db()
|
| 61 |
|
| 62 |
# ---------------------------------------------------------------------------
|
| 63 |
+
# 2. MODEL AUTO-TRAINING & ARTIFACT LOADING PIPELINE
|
| 64 |
# ---------------------------------------------------------------------------
|
| 65 |
MODEL_PATH = 'steel_model.joblib'
|
| 66 |
SCALER_PATH = 'scaler.joblib'
|
| 67 |
COLUMNS_PATH = 'model_columns.joblib'
|
| 68 |
|
| 69 |
+
feature_columns = [
|
| 70 |
+
'Lagging_Current_Reactive_Power_kVarh', 'Leading_Current_Reactive_Power_kVarh',
|
| 71 |
+
'Lagging_Current_Power_Factor', 'Leading_Current_Power_Factor', 'NSM',
|
| 72 |
+
'Hour', 'Month', 'Reactive_Power_Ratio', 'Power_Factor_Ratio',
|
| 73 |
+
'WeekStatus_Weekend', 'Day_of_week_Monday', 'Day_of_week_Saturday',
|
| 74 |
+
'Day_of_week_Sunday', 'Day_of_week_Thursday', 'Day_of_week_Tuesday',
|
| 75 |
+
'Day_of_week_Wednesday', 'Load_Type_Maximum_Load', 'Load_Type_Medium_Load'
|
| 76 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
def clean_cols(df_input):
|
| 79 |
+
df = df_input.copy()
|
|
|
|
|
|
|
|
|
|
| 80 |
df.columns = (
|
| 81 |
df.columns.str.strip()
|
| 82 |
.str.replace(' ', '_')
|
|
|
|
| 84 |
.str.replace(')', '', regex=False)
|
| 85 |
.str.replace('.', '_', regex=False)
|
| 86 |
)
|
| 87 |
+
return df
|
| 88 |
+
|
| 89 |
+
def build_or_load_artifacts():
|
| 90 |
+
if os.path.exists(MODEL_PATH) and os.path.exists(SCALER_PATH) and os.path.exists(COLUMNS_PATH):
|
| 91 |
+
try:
|
| 92 |
+
m = joblib.load(MODEL_PATH)
|
| 93 |
+
s = joblib.load(SCALER_PATH)
|
| 94 |
+
c = joblib.load(COLUMNS_PATH)
|
| 95 |
+
return m, s, c
|
| 96 |
+
except Exception:
|
| 97 |
+
pass
|
| 98 |
+
|
| 99 |
+
# If artifacts are missing, build model from dataset or realistic synthesis
|
| 100 |
+
csv_file = "Steel_industry_data.csv"
|
| 101 |
+
if os.path.exists(csv_file):
|
| 102 |
+
df_train = pd.read_csv(csv_file)
|
| 103 |
+
df_train = clean_cols(df_train)
|
| 104 |
+
else:
|
| 105 |
+
# Synthesize dataset matching standard UCI Steel Industry bounds
|
| 106 |
+
np.random.seed(42)
|
| 107 |
+
n = 5000
|
| 108 |
+
lag_kvarh = np.random.exponential(13.0, n)
|
| 109 |
+
lead_kvarh = np.random.exponential(3.8, n)
|
| 110 |
+
lag_pf = np.random.uniform(50, 100, n)
|
| 111 |
+
lead_pf = np.random.uniform(50, 100, n)
|
| 112 |
+
nsm = np.random.uniform(0, 86400, n)
|
| 113 |
+
hour = (nsm // 3600).astype(int)
|
| 114 |
+
month = np.random.randint(1, 13, n)
|
| 115 |
+
dow = np.random.choice(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], n)
|
| 116 |
+
load = np.random.choice(['Light_Load', 'Medium_Load', 'Maximum_Load'], n)
|
| 117 |
+
|
| 118 |
+
usage_kwh = (
|
| 119 |
+
2.5 +
|
| 120 |
+
1.2 * lag_kvarh +
|
| 121 |
+
0.12 * lead_kvarh +
|
| 122 |
+
0.15 * lag_pf +
|
| 123 |
+
np.where(load == 'Maximum_Load', 28.0, np.where(load == 'Medium_Load', 14.0, 0.0)) +
|
| 124 |
+
np.random.normal(0, 1.2, n)
|
| 125 |
+
)
|
| 126 |
+
usage_kwh = np.maximum(usage_kwh, 0.0)
|
| 127 |
+
|
| 128 |
+
df_train = pd.DataFrame({
|
| 129 |
+
'Lagging_Current_Reactive_Power_kVarh': lag_kvarh,
|
| 130 |
+
'Leading_Current_Reactive_Power_kVarh': lead_kvarh,
|
| 131 |
+
'Lagging_Current_Power_Factor': lag_pf,
|
| 132 |
+
'Leading_Current_Power_Factor': lead_pf,
|
| 133 |
+
'NSM': nsm,
|
| 134 |
+
'Hour': hour,
|
| 135 |
+
'Month': month,
|
| 136 |
+
'Day_of_week': dow,
|
| 137 |
+
'Load_Type': load,
|
| 138 |
+
'Usage_kWh': usage_kwh
|
| 139 |
+
})
|
| 140 |
+
|
| 141 |
+
eps = 1e-5
|
| 142 |
+
df_train['Reactive_Power_Ratio'] = df_train['Lagging_Current_Reactive_Power_kVarh'] / (df_train['Leading_Current_Reactive_Power_kVarh'] + eps)
|
| 143 |
+
df_train['Power_Factor_Ratio'] = df_train['Lagging_Current_Power_Factor'] / (df_train['Leading_Current_Power_Factor'] + eps)
|
| 144 |
+
df_train['WeekStatus'] = np.where(df_train['Day_of_week'].isin(['Saturday', 'Sunday']), 'Weekend', 'Weekday')
|
| 145 |
+
|
| 146 |
+
df_enc = pd.get_dummies(df_train, drop_first=True)
|
| 147 |
+
X_proc = pd.DataFrame(0, index=df_train.index, columns=feature_columns)
|
| 148 |
+
for col in feature_columns:
|
| 149 |
+
if col in df_enc.columns:
|
| 150 |
+
X_proc[col] = df_enc[col]
|
| 151 |
+
|
| 152 |
+
scaler = StandardScaler()
|
| 153 |
+
X_scaled = scaler.fit_transform(X_proc)
|
| 154 |
+
|
| 155 |
+
model = RandomForestRegressor(n_estimators=50, max_depth=12, random_state=42)
|
| 156 |
+
model.fit(X_scaled, df_train['Usage_kWh'])
|
| 157 |
+
|
| 158 |
+
joblib.dump(model, MODEL_PATH)
|
| 159 |
+
joblib.dump(scaler, SCALER_PATH)
|
| 160 |
+
joblib.dump(feature_columns, COLUMNS_PATH)
|
| 161 |
+
|
| 162 |
+
return model, scaler, feature_columns
|
| 163 |
+
|
| 164 |
+
model, scaler, feature_columns = build_or_load_artifacts()
|
| 165 |
+
|
| 166 |
+
# ---------------------------------------------------------------------------
|
| 167 |
+
# 3. FEATURE ENGINEERING & PREDICTION PIPELINE
|
| 168 |
+
# ---------------------------------------------------------------------------
|
| 169 |
+
def preprocess_and_predict(df_raw):
|
| 170 |
+
df = clean_cols(df_raw)
|
| 171 |
|
| 172 |
if 'date' in df.columns:
|
| 173 |
df['date'] = pd.to_datetime(df['date'], format='%d/%m/%Y %H:%M', errors='coerce')
|
| 174 |
df['Hour'] = df['date'].dt.hour.fillna(12).astype(int)
|
| 175 |
df['Month'] = df['date'].dt.month.fillna(1).astype(int)
|
| 176 |
else:
|
| 177 |
+
if 'Hour' not in df.columns:
|
| 178 |
+
df['Hour'] = 12
|
| 179 |
+
if 'Month' not in df.columns:
|
| 180 |
+
df['Month'] = 1
|
| 181 |
|
| 182 |
eps = 1e-5
|
| 183 |
df['Reactive_Power_Ratio'] = (
|
|
|
|
| 189 |
(df['Leading_Current_Power_Factor'] + eps)
|
| 190 |
)
|
| 191 |
|
| 192 |
+
if 'Day_of_week' in df.columns:
|
| 193 |
+
df['WeekStatus'] = np.where(df['Day_of_week'].isin(['Saturday', 'Sunday']), 'Weekend', 'Weekday')
|
| 194 |
+
else:
|
| 195 |
+
df['WeekStatus'] = 'Weekday'
|
| 196 |
+
df['Day_of_week'] = 'Monday'
|
| 197 |
+
|
| 198 |
df_encoded = pd.get_dummies(df, drop_first=True)
|
| 199 |
|
|
|
|
| 200 |
X_processed = pd.DataFrame(0, index=df.index, columns=feature_columns)
|
| 201 |
for col in feature_columns:
|
| 202 |
if col in df_encoded.columns:
|
|
|
|
| 222 |
'DocTitle',
|
| 223 |
parent=styles['Heading1'],
|
| 224 |
fontName='Helvetica-Bold',
|
| 225 |
+
fontSize=18,
|
| 226 |
textColor=colors.HexColor('#0f172a'),
|
| 227 |
spaceAfter=12
|
| 228 |
)
|
|
|
|
| 233 |
fontName='Helvetica',
|
| 234 |
fontSize=10,
|
| 235 |
textColor=colors.HexColor('#64748b'),
|
| 236 |
+
spaceAfter=18
|
| 237 |
)
|
| 238 |
|
| 239 |
+
elements = [
|
| 240 |
+
Paragraph("Steel Plant Energy & CO2 Audit Report", title_style),
|
| 241 |
+
Paragraph(f"Generated on: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} | Hugging Face Spaces Engine", subtitle_style)
|
| 242 |
+
]
|
| 243 |
|
|
|
|
| 244 |
summary_data = [
|
| 245 |
["Metric Description", "Value"],
|
| 246 |
["Total Processed Records", f"{summary_stats['total_records']}"],
|
| 247 |
["Mean Electricity Demand (kWh)", f"{summary_stats['mean_kwh']:.2f} kWh"],
|
| 248 |
["Max Electricity Demand (kWh)", f"{summary_stats['max_kwh']:.2f} kWh"],
|
| 249 |
["Total Estimated CO2 Footprint", f"{summary_stats['total_co2']:.4f} Metric Tonnes"],
|
| 250 |
+
["Mitigated Potential CO2 Saved (10% Peak Drop)", f"{summary_stats['mitigated_co2']:.4f} Metric Tonnes"]
|
| 251 |
]
|
| 252 |
|
| 253 |
+
st = Table(summary_data, colWidths=[280, 220])
|
| 254 |
st.setStyle(TableStyle([
|
| 255 |
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#1e293b')),
|
| 256 |
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
|
| 257 |
('FONTNAME', (0, 0), (-1, 0), 'Helvetica-Bold'),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 258 |
('GRID', (0, 0), (-1, -1), 0.5, colors.HexColor('#cbd5e1')),
|
| 259 |
+
('TOPPADDING', (0, 0), (-1, -1), 6),
|
| 260 |
+
('BOTTOMPADDING', (0, 0), (-1, -1), 6),
|
| 261 |
]))
|
| 262 |
|
| 263 |
elements.append(st)
|
| 264 |
+
elements.append(Spacer(1, 15))
|
| 265 |
|
|
|
|
| 266 |
elements.append(Paragraph("Sample Predictions Preview (First 10 Rows)", styles['Heading2']))
|
| 267 |
preview_df = df_results[['Predicted_Usage_kWh', 'Estimated_CO2_Tonnes']].head(10).reset_index()
|
| 268 |
|
|
|
|
| 270 |
for _, row in preview_df.iterrows():
|
| 271 |
preview_data.append([str(int(row['index'] + 1)), f"{row['Predicted_Usage_kWh']:.2f}", f"{row['Estimated_CO2_Tonnes']:.6f}"])
|
| 272 |
|
| 273 |
+
pt = Table(preview_data, colWidths=[80, 210, 210])
|
| 274 |
pt.setStyle(TableStyle([
|
| 275 |
('BACKGROUND', (0, 0), (-1, 0), colors.HexColor('#0284c7')),
|
| 276 |
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
|
|
|
|
| 303 |
'Hour': [hour],
|
| 304 |
'Month': [month],
|
| 305 |
'Day_of_week': [day_of_week],
|
| 306 |
+
'Load_Type': [load_type]
|
|
|
|
| 307 |
}
|
| 308 |
df_single = pd.DataFrame(data)
|
| 309 |
res = preprocess_and_predict(df_single)
|
|
|
|
| 311 |
kwh = float(res['Predicted_Usage_kWh'].iloc[0])
|
| 312 |
co2 = float(res['Estimated_CO2_Tonnes'].iloc[0])
|
| 313 |
|
| 314 |
+
# Optional Database Logging
|
| 315 |
conn = get_db_connection()
|
| 316 |
if conn:
|
| 317 |
try:
|
|
|
|
| 323 |
conn.commit()
|
| 324 |
cursor.close()
|
| 325 |
conn.close()
|
| 326 |
+
except Exception:
|
| 327 |
+
pass
|
| 328 |
|
| 329 |
return f"{kwh:.2f} kWh", f"{co2:.6f} Metric Tonnes"
|
| 330 |
|
|
|
|
| 336 |
df_results = preprocess_and_predict(df_raw)
|
| 337 |
|
| 338 |
total_records = len(df_results)
|
|
|
|
|
|
|
|
|
|
| 339 |
|
| 340 |
+
# Use ground-truth Usage_kWh if present in uploaded CSV, else use predictions
|
| 341 |
+
cleaned_raw_cols = [c.strip().replace(' ', '_').replace('(', '').replace(')', '').replace('.', '_') for c in df_raw.columns]
|
| 342 |
+
if 'Usage_kWh' in cleaned_raw_cols:
|
| 343 |
+
target_col = df_results['Usage_kWh'] if 'Usage_kWh' in df_results.columns else df_results['Predicted_Usage_kWh']
|
| 344 |
+
else:
|
| 345 |
+
target_col = df_results['Predicted_Usage_kWh']
|
| 346 |
+
|
| 347 |
+
mean_kwh = float(target_col.mean())
|
| 348 |
+
max_kwh = float(target_col.max())
|
| 349 |
+
total_co2 = float((target_col * 0.00042).sum())
|
| 350 |
+
|
| 351 |
+
# Mitigation simulation (10% demand drop on peak intervals > mean)
|
| 352 |
+
mitigated_kwh = target_col.copy()
|
| 353 |
mitigated_kwh[mitigated_kwh > mean_kwh] *= 0.90
|
| 354 |
+
mitigated_co2 = float(total_co2 - (mitigated_kwh * 0.00042).sum())
|
| 355 |
|
| 356 |
summary_stats = {
|
| 357 |
'total_records': total_records,
|
|
|
|
| 365 |
|
| 366 |
summary_text = f"""
|
| 367 |
### 📊 Analysis Summary
|
| 368 |
+
* **Total Processed Records:** {total_records:,}
|
| 369 |
+
* **Average Demand:** {mean_kwh:.2f} kWh
|
| 370 |
* **Peak Demand Recorded:** {max_kwh:.2f} kWh
|
| 371 |
* **Total Estimated Carbon Footprint:** {total_co2:.4f} Metric Tonnes
|
| 372 |
* **Potential CO2 Saved (via Peak Factor Mitigation):** {mitigated_co2:.4f} Metric Tonnes
|
| 373 |
"""
|
| 374 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 375 |
return df_results, summary_text, pdf_path
|
| 376 |
|
| 377 |
# ---------------------------------------------------------------------------
|
| 378 |
+
# 6. SLEEK & GLOSSY GRADIO UI
|
| 379 |
# ---------------------------------------------------------------------------
|
| 380 |
custom_css = """
|
|
|
|
| 381 |
body, .gradio-container {
|
| 382 |
background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%) !important;
|
| 383 |
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif !important;
|
| 384 |
color: #f8fafc !important;
|
| 385 |
}
|
| 386 |
|
|
|
|
| 387 |
.glass-panel {
|
| 388 |
background: rgba(30, 41, 59, 0.7) !important;
|
| 389 |
backdrop-filter: blur(12px) !important;
|
|
|
|
| 390 |
border: 1px solid rgba(255, 255, 255, 0.1) !important;
|
| 391 |
border-radius: 16px !important;
|
|
|
|
| 392 |
padding: 20px !important;
|
| 393 |
margin-bottom: 20px !important;
|
| 394 |
}
|
| 395 |
|
|
|
|
| 396 |
.sidebar-panel {
|
| 397 |
background: rgba(15, 23, 42, 0.85) !important;
|
| 398 |
border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
|
|
|
|
| 400 |
border-radius: 16px !important;
|
| 401 |
}
|
| 402 |
|
|
|
|
| 403 |
.btn-primary {
|
| 404 |
background: linear-gradient(90deg, #0284c7 0%, #0369a1 100%) !important;
|
| 405 |
border: none !important;
|
|
|
|
| 407 |
font-weight: 600 !important;
|
| 408 |
border-radius: 10px !important;
|
| 409 |
box-shadow: 0 4px 14px 0 rgba(2, 132, 199, 0.39) !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
}
|
| 411 |
"""
|
| 412 |
|
|
|
|
| 419 |
)
|
| 420 |
|
| 421 |
with gr.Row():
|
| 422 |
+
# SIDEBAR CONTROL PANEL
|
| 423 |
with gr.Column(scale=1, elem_classes=["sidebar-panel"]):
|
| 424 |
gr.Markdown("### ⚙️ Input Control Sidebar")
|
| 425 |
gr.Markdown("Configure manual parameters or run batch processes directly.")
|
|
|
|
| 445 |
|
| 446 |
predict_btn = gr.Button("🚀 Predict Single Record", elem_classes=["btn-primary"])
|
| 447 |
|
| 448 |
+
# MAIN WORKFLOW AREA
|
| 449 |
with gr.Column(scale=3):
|
| 450 |
with gr.Tabs():
|
| 451 |
+
# TAB 1: CSV UPLOAD & AUDIT EXPORT
|
| 452 |
with gr.TabItem("📂 Batch CSV Upload & PDF Export"):
|
| 453 |
with gr.Group(elem_classes=["glass-panel"]):
|
| 454 |
gr.Markdown("### Upload Steel Industry Data CSV")
|
|
|
|
| 462 |
summary_output = gr.Markdown(value="*Upload a CSV to view analysis summary.*")
|
| 463 |
pdf_download = gr.File(label="📄 Download PDF Audit Report")
|
| 464 |
|
| 465 |
+
# TAB 2: SINGLE PREDICTION RESULT
|
| 466 |
with gr.TabItem("🎯 Single Record Result"):
|
| 467 |
with gr.Group(elem_classes=["glass-panel"]):
|
| 468 |
gr.Markdown("### Single Inspection Prediction Result")
|
| 469 |
out_kwh = gr.Textbox(label="Predicted Energy Consumption (Usage_kWh)", interactive=False)
|
| 470 |
out_co2 = gr.Textbox(label="Estimated Carbon Emissions (Tonnes CO2)", interactive=False)
|
| 471 |
|
| 472 |
+
# Inputs list for single predictions
|
| 473 |
+
single_inputs = [lag_kvarh, lead_kvarh, lag_pf, lead_pf, nsm, hour, month, day_of_week, load_type]
|
| 474 |
+
single_outputs = [out_kwh, out_co2]
|
| 475 |
+
|
| 476 |
+
# Explicit button click
|
| 477 |
predict_btn.click(
|
| 478 |
fn=handle_single_prediction,
|
| 479 |
+
inputs=single_inputs,
|
| 480 |
+
outputs=single_outputs
|
| 481 |
)
|
| 482 |
|
| 483 |
+
# Real-time change updates for sliders and numbers
|
| 484 |
+
for inp in single_inputs:
|
| 485 |
+
inp.change(
|
| 486 |
+
fn=handle_single_prediction,
|
| 487 |
+
inputs=single_inputs,
|
| 488 |
+
outputs=single_outputs
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
# Auto-run prediction on initial page load (prevents blank textboxes)
|
| 492 |
+
demo.load(
|
| 493 |
+
fn=handle_single_prediction,
|
| 494 |
+
inputs=single_inputs,
|
| 495 |
+
outputs=single_outputs
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
# Batch CSV handling
|
| 499 |
process_csv_btn.click(
|
| 500 |
fn=handle_csv_upload,
|
| 501 |
inputs=[file_input],
|