Update app.py
Browse files
app.py
CHANGED
|
@@ -12,7 +12,7 @@ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
|
| 12 |
from reportlab.lib import colors
|
| 13 |
|
| 14 |
# ---------------------------------------------------------------------------
|
| 15 |
-
# 1.
|
| 16 |
# ---------------------------------------------------------------------------
|
| 17 |
DB_HOST = os.getenv("MYSQL_HOST", "sql6.freedatabase.com")
|
| 18 |
DB_USER = os.getenv("MYSQL_USER", "your_username")
|
|
@@ -23,12 +23,16 @@ DB_PORT = int(os.getenv("MYSQL_PORT", 3306))
|
|
| 23 |
def get_db_connection():
|
| 24 |
try:
|
| 25 |
conn = mysql.connector.connect(
|
| 26 |
-
host=DB_HOST,
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
)
|
| 29 |
return conn
|
| 30 |
except Exception as e:
|
| 31 |
-
print(f"[DB Warning]
|
| 32 |
return None
|
| 33 |
|
| 34 |
def init_db():
|
|
@@ -37,12 +41,11 @@ def init_db():
|
|
| 37 |
try:
|
| 38 |
cursor = conn.cursor()
|
| 39 |
cursor.execute("""
|
| 40 |
-
CREATE TABLE IF NOT EXISTS
|
| 41 |
id INT AUTO_INCREMENT PRIMARY KEY,
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
anomaly_status VARCHAR(50),
|
| 46 |
timestamp DATETIME
|
| 47 |
)
|
| 48 |
""")
|
|
@@ -55,12 +58,13 @@ def init_db():
|
|
| 55 |
init_db()
|
| 56 |
|
| 57 |
# ---------------------------------------------------------------------------
|
| 58 |
-
# 2. MODEL & ARTIFACT
|
| 59 |
# ---------------------------------------------------------------------------
|
| 60 |
MODEL_PATH = 'steel_model.joblib'
|
| 61 |
SCALER_PATH = 'scaler.joblib'
|
| 62 |
COLUMNS_PATH = 'model_columns.joblib'
|
| 63 |
|
|
|
|
| 64 |
if os.path.exists(MODEL_PATH) and os.path.exists(SCALER_PATH) and os.path.exists(COLUMNS_PATH):
|
| 65 |
model = joblib.load(MODEL_PATH)
|
| 66 |
scaler = joblib.load(SCALER_PATH)
|
|
@@ -68,6 +72,7 @@ if os.path.exists(MODEL_PATH) and os.path.exists(SCALER_PATH) and os.path.exists
|
|
| 68 |
else:
|
| 69 |
from sklearn.ensemble import RandomForestRegressor
|
| 70 |
from sklearn.preprocessing import StandardScaler
|
|
|
|
| 71 |
feature_columns = [
|
| 72 |
'Lagging_Current_Reactive_Power_kVarh', 'Leading_Current_Reactive_Power_kVarh',
|
| 73 |
'Lagging_Current_Power_Factor', 'Leading_Current_Power_Factor', 'NSM',
|
|
@@ -78,15 +83,21 @@ else:
|
|
| 78 |
]
|
| 79 |
scaler = StandardScaler()
|
| 80 |
scaler.fit(np.zeros((10, len(feature_columns))))
|
| 81 |
-
model = RandomForestRegressor(n_estimators=10, random_state=42)
|
| 82 |
model.fit(np.zeros((10, len(feature_columns))), np.zeros(10))
|
| 83 |
|
| 84 |
# ---------------------------------------------------------------------------
|
| 85 |
-
# 3.
|
| 86 |
# ---------------------------------------------------------------------------
|
| 87 |
-
def
|
| 88 |
df = df_raw.copy()
|
| 89 |
-
df.columns =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
if 'date' in df.columns:
|
| 92 |
df['date'] = pd.to_datetime(df['date'], format='%d/%m/%Y %H:%M', errors='coerce')
|
|
@@ -97,10 +108,18 @@ def process_energy_data(df_raw, asset_name="General Steel Plant"):
|
|
| 97 |
df['Month'] = 1
|
| 98 |
|
| 99 |
eps = 1e-5
|
| 100 |
-
df['Reactive_Power_Ratio'] =
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
df_encoded = pd.get_dummies(df, drop_first=True)
|
|
|
|
|
|
|
| 104 |
X_processed = pd.DataFrame(0, index=df.index, columns=feature_columns)
|
| 105 |
for col in feature_columns:
|
| 106 |
if col in df_encoded.columns:
|
|
@@ -112,208 +131,302 @@ def process_energy_data(df_raw, asset_name="General Steel Plant"):
|
|
| 112 |
df['Predicted_Usage_kWh'] = np.round(predictions, 4)
|
| 113 |
df['Estimated_CO2_Tonnes'] = np.round(predictions * 0.00042, 6)
|
| 114 |
|
| 115 |
-
# Anomaly Detection (Baseline mean + 2*std threshold)
|
| 116 |
-
mean_val = df['Predicted_Usage_kWh'].mean()
|
| 117 |
-
std_val = df['Predicted_Usage_kWh'].std() if len(df) > 1 else 10.0
|
| 118 |
-
df['Status'] = df['Predicted_Usage_kWh'].apply(lambda x: '⚠️ PEAK ANOMALY' if x > (mean_val + 1.8 * std_val) else '✅ OPTIMAL')
|
| 119 |
-
|
| 120 |
return df
|
| 121 |
|
| 122 |
# ---------------------------------------------------------------------------
|
| 123 |
-
# 4.
|
| 124 |
# ---------------------------------------------------------------------------
|
| 125 |
-
def generate_pdf_report(df_results,
|
| 126 |
pdf_buffer = io.BytesIO()
|
| 127 |
doc = SimpleDocTemplate(pdf_buffer, pagesize=letter, rightMargin=36, leftMargin=36, topMargin=36, bottomMargin=36)
|
| 128 |
styles = getSampleStyleSheet()
|
| 129 |
|
| 130 |
-
title_style = ParagraphStyle(
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
elements = []
|
| 134 |
-
elements.append(Paragraph(
|
| 135 |
-
elements.append(Paragraph(f"Generated
|
| 136 |
|
|
|
|
| 137 |
summary_data = [
|
| 138 |
-
["
|
| 139 |
-
["Total
|
| 140 |
-
["Mean
|
| 141 |
-
["
|
| 142 |
-
["Total Estimated
|
| 143 |
-
["
|
| 144 |
-
["Estimated Savings via Peak Shaving", f"${metrics['savings']:.2f} USD"]
|
| 145 |
]
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
('BACKGROUND', (0,0), (-1,0), colors.HexColor('#1e293b')),
|
| 150 |
-
('TEXTCOLOR', (0,0), (-1,0), colors.whitesmoke),
|
| 151 |
-
('FONTNAME', (0,0), (-1,0), 'Helvetica-Bold'),
|
| 152 |
-
('
|
| 153 |
-
('
|
| 154 |
-
('
|
| 155 |
-
('
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
]))
|
| 157 |
-
|
|
|
|
| 158 |
doc.build(elements)
|
| 159 |
|
| 160 |
pdf_buffer.seek(0)
|
| 161 |
-
|
| 162 |
-
with open(
|
| 163 |
f.write(pdf_buffer.read())
|
| 164 |
-
|
|
|
|
| 165 |
|
| 166 |
# ---------------------------------------------------------------------------
|
| 167 |
-
# 5. GRADIO
|
| 168 |
# ---------------------------------------------------------------------------
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
with gr.Column(scale=2, elem_classes=["panel"]):
|
| 195 |
-
gr.Markdown("### Diagnostic Results & AI Recommendations")
|
| 196 |
-
asset_kwh_out = gr.Textbox(label="Predicted Energy Demand")
|
| 197 |
-
asset_co2_out = gr.Textbox(label="Carbon Footprint Impact")
|
| 198 |
-
asset_status_out = gr.Textbox(label="AI Health & Anomaly Status")
|
| 199 |
-
copilot_rec = gr.Markdown(value="*Run diagnostics to view automated AI peak-shaving recommendations.*")
|
| 200 |
|
| 201 |
-
|
| 202 |
-
with gr.TabItem("📂 Batch CSV & ISO 50001 Audit"):
|
| 203 |
-
with gr.Group(elem_classes=["panel"]):
|
| 204 |
-
gr.Markdown("### Upload Plant Telemetry CSV")
|
| 205 |
-
csv_file = gr.File(label="Upload Dataset (`Steel_industry_data.csv`)", file_types=[".csv"])
|
| 206 |
-
run_batch_btn = gr.Button("Process Audit & Generate ESG PDF", elem_classes=["btn-primary"])
|
| 207 |
-
|
| 208 |
-
with gr.Row():
|
| 209 |
-
batch_table = gr.Dataframe(label="Processed Predictions Preview")
|
| 210 |
-
with gr.Column():
|
| 211 |
-
batch_summary = gr.Markdown(value="*Upload data to see executive summary.*")
|
| 212 |
-
pdf_output = gr.File(label="📄 Download ISO 50001 Audit Report")
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
'Day_of_week': ['Wednesday']
|
| 237 |
-
})
|
| 238 |
-
res = process_energy_data(df_single, asset)
|
| 239 |
-
kwh = float(res['Predicted_Usage_kWh'].iloc[0])
|
| 240 |
-
co2 = float(res['Estimated_CO2_Tonnes'].iloc[0])
|
| 241 |
-
status = str(res['Status'].iloc[0])
|
| 242 |
-
|
| 243 |
-
rec = f"""
|
| 244 |
-
**AI Copilot Recommendations for {asset}:**
|
| 245 |
-
* **Status:** {status}
|
| 246 |
-
* **Actionable Insight:** Current reactive power ratio indicates inductive load stress. Stagger motor startup by 15 minutes to avoid peak utility demand surcharges.
|
| 247 |
-
* **Estimated Cost Savings:** $340 per shift.
|
| 248 |
-
"""
|
| 249 |
-
|
| 250 |
-
# Save to MySQL
|
| 251 |
-
conn = get_db_connection()
|
| 252 |
-
if conn:
|
| 253 |
-
try:
|
| 254 |
-
cur = conn.cursor()
|
| 255 |
-
cur.execute("INSERT INTO enterprise_audits (asset_name, predicted_kwh, co2_tonnes, anomaly_status, timestamp) VALUES (%s, %s, %s, %s, %s)",
|
| 256 |
-
(asset, kwh, co2, status, datetime.datetime.now()))
|
| 257 |
-
conn.commit()
|
| 258 |
-
cur.close()
|
| 259 |
-
conn.close()
|
| 260 |
-
except Exception:
|
| 261 |
-
pass
|
| 262 |
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
'max_kwh': max_kwh,
|
| 282 |
-
'total_co2': total_co2,
|
| 283 |
-
'anomaly_count': anomaly_count,
|
| 284 |
-
'savings': savings
|
| 285 |
-
}
|
| 286 |
-
|
| 287 |
-
pdf_path = generate_pdf_report(df_res, "Plant Alpha Steel Works", metrics)
|
| 288 |
-
|
| 289 |
-
summary_md = f"""
|
| 290 |
-
### 📊 Executive ESG & Energy Summary
|
| 291 |
-
* **Total Records Processed:** {total_records}
|
| 292 |
-
* **Average Demand:** {mean_kwh:.2f} kWh
|
| 293 |
-
* **Peak Load Spike:** {max_kwh:.2f} kWh
|
| 294 |
-
* **Total Carbon Emissions:** {total_co2:.4f} Metric Tonnes
|
| 295 |
-
* **Anomalies Flagged:** {anomaly_count} events
|
| 296 |
-
* **Projected Savings (Peak Shaving):** ${savings:.2f}
|
| 297 |
-
"""
|
| 298 |
-
|
| 299 |
-
return df_res, summary_md, pdf_path
|
| 300 |
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
return f"""
|
| 304 |
-
### ✅ Automated Purchase Order Generated Successfully
|
| 305 |
-
* **PO Reference ID:** `{po_id}`
|
| 306 |
-
* **Vendor / Supplier:** {supplier}
|
| 307 |
-
* **Category:** {category}
|
| 308 |
-
* **Quantity / Scope:** {qty} units
|
| 309 |
-
* **Compliance & Tax Check:** W-8/W-9 verified via Tipalti secure compliance engine[cite: 18].
|
| 310 |
-
* **ERP Synchronization:** Synced with SAP/Oracle successfully.
|
| 311 |
-
* **ESG Carbon Score:** Verified low-carbon supplier (Score: A+ / 0.12 kgCO2e per unit).
|
| 312 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
|
| 318 |
if __name__ == "__main__":
|
| 319 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 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")
|
|
|
|
| 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():
|
|
|
|
| 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 |
""")
|
|
|
|
| 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)
|
|
|
|
| 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',
|
|
|
|
| 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')
|
|
|
|
| 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:
|
|
|
|
| 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)
|