VectorV17 commited on
Commit
0bea3e4
·
verified ·
1 Parent(s): dcf8eb4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +299 -186
app.py CHANGED
@@ -12,7 +12,7 @@ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
12
  from reportlab.lib import colors
13
 
14
  # ---------------------------------------------------------------------------
15
- # 1. ENTERPRISE DATABASE CONFIGURATION (MySQL / FreeDatabase.com)
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, user=DB_USER, password=DB_PASS,
27
- database=DB_NAME, port=DB_PORT, connect_timeout=5
 
 
 
 
28
  )
29
  return conn
30
  except Exception as e:
31
- print(f"[DB Warning] Connection skipped: {e}")
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 enterprise_audits (
41
  id INT AUTO_INCREMENT PRIMARY KEY,
42
- asset_name VARCHAR(100),
43
- predicted_kwh FLOAT,
44
- co2_tonnes FLOAT,
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 INITIALIZATION
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. PREDICTION & ANOMALY DETECTION ENGINE (iFactory Inspired)
86
  # ---------------------------------------------------------------------------
87
- def process_energy_data(df_raw, asset_name="General Steel Plant"):
88
  df = df_raw.copy()
89
- df.columns = df.columns.str.strip().str.replace(' ', '_').str.replace('(', '').str.replace(')', '').str.replace('.', '_')
 
 
 
 
 
 
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'] = df['Lagging_Current_Reactive_Power_kVarh'] / (df['Leading_Current_Reactive_Power_kVarh'] + eps)
101
- df['Power_Factor_Ratio'] = df['Lagging_Current_Power_Factor'] / (df['Leading_Current_Power_Factor'] + eps)
 
 
 
 
 
 
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. ISO 50001 & ESG PDF REPORT GENERATOR
124
  # ---------------------------------------------------------------------------
125
- def generate_pdf_report(df_results, asset_name, metrics):
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('Title', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=18, textColor=colors.HexColor('#0f172a'))
131
- sub_style = ParagraphStyle('Sub', parent=styles['Normal'], fontName='Helvetica', fontSize=10, textColor=colors.HexColor('#64748b'), spaceAfter=15)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
132
 
133
  elements = []
134
- elements.append(Paragraph(f"ISO 50001 Energy & Carbon Audit Report: {asset_name}", title_style))
135
- elements.append(Paragraph(f"Generated via SteelPulse AI Engine | Timestamp: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", sub_style))
136
 
 
137
  summary_data = [
138
- ["Performance Metric", "Measured Value"],
139
- ["Total Records Analyzed", f"{metrics['total_records']}"],
140
- ["Mean Energy Demand", f"{metrics['mean_kwh']:.2f} kWh"],
141
- ["Peak Load Spike", f"{metrics['max_kwh']:.2f} kWh"],
142
- ["Total Estimated Carbon (Scope 2)", f"{metrics['total_co2']:.4f} Tonnes CO2"],
143
- ["Anomalies Detected", f"{metrics['anomaly_count']} instances"],
144
- ["Estimated Savings via Peak Shaving", f"${metrics['savings']:.2f} USD"]
145
  ]
146
 
147
- t = Table(summary_data, colWidths=[280, 240])
148
- t.setStyle(TableStyle([
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
- ('BOTTOMPADDING', (0,0), (-1,-1), 6),
153
- ('TOPPADDING', (0,0), (-1,-1), 6),
154
- ('BACKGROUND', (0,1), (-1,-1), colors.HexColor('#f8fafc')),
155
- ('GRID', (0,0), (-1,-1), 0.5, colors.HexColor('#cbd5e1')),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  ]))
157
- elements.append(t)
 
158
  doc.build(elements)
159
 
160
  pdf_buffer.seek(0)
161
- path = "/tmp/steelpulse_audit_report.pdf"
162
- with open(path, "wb") as f:
163
  f.write(pdf_buffer.read())
164
- return path
 
165
 
166
  # ---------------------------------------------------------------------------
167
- # 5. GRADIO UI WITH INDUSTRIAL COPILOT PANELS
168
  # ---------------------------------------------------------------------------
169
- custom_css = """
170
- body, .gradio-container { background: #0b0f19 !important; color: #f1f5f9 !important; font-family: 'Inter', sans-serif !important; }
171
- .panel { background: #131c2e !important; border: 1px solid #1e293b !important; border-radius: 12px !important; padding: 20px !important; }
172
- .btn-primary { background: linear-gradient(90deg, #2563eb 0%, #1d4ed8 100%) !important; color: white !important; font-weight: 600 !important; border-radius: 8px !important; }
173
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
175
- with gr.Blocks(css=custom_css, title="SteelPulse Enterprise AI") as demo:
176
- gr.Markdown("# 🏭 SteelPulse Enterprise Intelligence & Energy Copilot")
177
- gr.Markdown("### Industrial-Grade Energy Forecasting, Asset Profiling, and Procurement Carbon Tracking")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
- with gr.Tabs():
180
- # TAB 1: ASSET-LEVEL REAL-TIME MONITORING (iFactory style)
181
- with gr.TabItem("⚡ Asset Energy Profiler & Anomaly Detection"):
182
- with gr.Row():
183
- with gr.Column(scale=1, elem_classes=["panel"]):
184
- gr.Markdown("### Machine Asset Parameters")
185
- asset_selector = gr.Dropdown(choices=["Electric Arc Furnace #1", "Rolling Mill Line A", "Compressor Bank #2", "Oxygen Plant Air Separation"], value="Electric Arc Furnace #1", label="Select Plant Asset")
186
- lag_kvarh = gr.Number(label="Lagging Reactive Power (kVarh)", value=14.2)
187
- lead_kvarh = gr.Number(label="Leading Reactive Power (kVarh)", value=1.8)
188
- lag_pf = gr.Slider(0, 100, label="Lagging Power Factor (%)", value=82.5)
189
- lead_pf = gr.Slider(0, 100, label="Leading Power Factor (%)", value=96.0)
190
- nsm = gr.Number(label="Seconds from Midnight (NSM)", value=42000)
191
- load_type = gr.Dropdown(['Light_Load', 'Medium_Load', 'Maximum_Load'], value='Maximum_Load', label="Load Classification")
192
- predict_asset_btn = gr.Button("Run Asset Diagnostics", elem_classes=["btn-primary"])
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
- # TAB 2: BATCH CSV AUDIT & ESG REPORTING
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
- # TAB 3: PROCUREMENT & VENDOR CARBON COPILOT (Hyperbots / Tipalti style)
215
- with gr.TabItem("🤝 Procurement & Supplier ESG Copilot"):
216
- with gr.Group(elem_classes=["panel"]):
217
- gr.Markdown("### AI Purchase Requisition (PR) & Vendor Carbon Matching")
218
- supplier_name = gr.Textbox(label="Supplier Name / ID", value="Global Scrap Metals & Alloys Corp.")
219
- material_type = gr.Dropdown(choices=["Recycled Steel Scrap (Grade A)", "Ferro-Alloys", "High-Voltage Grid Power", "Industrial Lubricants"], label="Procurement Category")
220
- order_volume = gr.Number(label="Order Quantity (Tonnes / kWh)", value=500)
221
- po_generate_btn = gr.Button("Auto-Generate Compliant PO & Verify Vendor ESG", elem_classes=["btn-primary"])
222
-
223
- po_result_box = gr.Markdown(value="*Configure procurement parameters and generate automated PO.*")
224
 
225
- # --- EVENT HANDLERS ---
226
- def handle_asset_prediction(asset, l_kvarh, ld_kvarh, l_pf, ld_pf, n, l_type):
227
- df_single = pd.DataFrame({
228
- 'Lagging_Current_Reactive_Power_kVarh': [l_kvarh],
229
- 'Leading_Current_Reactive_Power_kVarh': [ld_kvarh],
230
- 'Lagging_Current_Power_Factor': [l_pf],
231
- 'Leading_Current_Power_Factor': [ld_pf],
232
- 'NSM': [n],
233
- 'Hour': [14], 'Month': [6],
234
- 'Load_Type': [l_type],
235
- 'WeekStatus': ['Weekday'],
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
- return f"{kwh:.2f} kWh", f"{co2:.6f} Tonnes", status, rec
 
 
 
 
 
 
264
 
265
- def handle_batch_audit(file):
266
- if file is None:
267
- return None, "Please upload a valid CSV file.", None
268
- df_raw = pd.read_csv(file.name)
269
- df_res = process_energy_data(df_raw)
270
-
271
- total_records = len(df_res)
272
- mean_kwh = df_res['Predicted_Usage_kWh'].mean()
273
- max_kwh = df_res['Predicted_Usage_kWh'].max()
274
- total_co2 = df_res['Estimated_CO2_Tonnes'].sum()
275
- anomaly_count = (df_res['Status'] == '⚠️ PEAK ANOMALY').sum()
276
- savings = anomaly_count * 125.50
277
-
278
- metrics = {
279
- 'total_records': total_records,
280
- 'mean_kwh': mean_kwh,
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
- def handle_procurement_copilot(supplier, category, qty):
302
- po_id = f"PO-2026-{np.random.randint(1000, 9999)}"
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
- predict_asset_btn.click(handle_asset_prediction, inputs=[asset_selector, lag_kvarh, lead_kvarh, lag_pf, lead_pf, nsm, load_type], outputs=[asset_kwh_out, asset_co2_out, asset_status_out, copilot_rec])
315
- run_batch_btn.click(handle_batch_audit, inputs=[csv_file], outputs=[batch_table, batch_summary, pdf_output])
316
- po_generate_btn.click(handle_procurement_copilot, inputs=[supplier_name, material_type, order_volume], outputs=[po_result_box])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)