VectorV17 commited on
Commit
30c63f0
·
verified ·
1 Parent(s): cd8e0eb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +410 -157
app.py CHANGED
@@ -1,179 +1,432 @@
1
- import gradio as gr
 
 
 
2
  import pandas as pd
3
  import numpy as np
4
- from sklearn.ensemble import RandomForestRegressor
5
- import tempfile
6
- import os
 
 
 
7
 
8
- # --------------------------------------------------------------------
9
- # 1. MODEL TRAINING & INITIALIZATION (Real Dataset Schema)
10
- # --------------------------------------------------------------------
11
- def build_baseline_model():
12
- np.random.seed(42)
13
- n = 1000
14
- df = pd.DataFrame({
15
- 'Lagging_Current_Reactive_Power_kVARh': np.random.uniform(0.0, 95.0, n),
16
- 'Leading_Current_Reactive_Power_kVARh': np.random.uniform(0.0, 27.0, n),
17
- 'Lagging_Current_Power_Factor': np.random.uniform(50.0, 100.0, n),
18
- 'Leading_Current_Power_Factor': np.random.uniform(50.0, 100.0, n),
19
- 'NSM': np.random.randint(0, 86400, n),
20
- 'Usage_kWh': np.random.uniform(2.0, 150.0, n)
21
- })
22
-
23
- X = df[['Lagging_Current_Reactive_Power_kVARh', 'Leading_Current_Reactive_Power_kVARh',
24
- 'Lagging_Current_Power_Factor', 'Leading_Current_Power_Factor', 'NSM']]
25
- y = df['Usage_kWh']
26
-
27
- model = RandomForestRegressor(n_estimators=20, random_state=42)
28
- model.fit(X, y)
29
- return model
30
-
31
- model = build_baseline_model()
32
-
33
- # --------------------------------------------------------------------
34
- # 2. INFERENCE & REPORT FUNCTIONS
35
- # --------------------------------------------------------------------
36
- def predict_single(lagging_kvarh, leading_kvarh, lagging_pf, leading_pf, nsm, hour, month):
37
- features = pd.DataFrame([[lagging_kvarh, leading_kvarh, lagging_pf, leading_pf, nsm]],
38
- columns=['Lagging_Current_Reactive_Power_kVARh', 'Leading_Current_Reactive_Power_kVARh',
39
- 'Lagging_Current_Power_Factor', 'Leading_Current_Power_Factor', 'NSM'])
40
-
41
- predicted_kwh = float(model.predict(features)[0])
42
- co2_emissions = predicted_kwh * 0.00042 # Standard grid emission conversion factor (Tonnes CO2)
43
-
44
- # Power Factor Health Status
45
- if lagging_pf >= 85.0 and leading_pf >= 85.0:
46
- status_html = '🟢 OPTIMAL POWER FACTOR (Efficient)'
47
- elif lagging_pf >= 70.0:
48
- status_html = '🟡 MODERATE POWER FACTOR (Review Recommended)'
49
- else:
50
- status_html = '🔴 HIGH REACTIVE LOSS (Capacitor Bank Alert)'
51
-
52
- return f"{predicted_kwh:.2f} kWh", f"{co2_emissions:.6f} Metric Tonnes", status_html
53
 
54
- def process_batch(file_obj):
55
- if file_obj is None:
56
- return "No file uploaded", None, "Upload a valid CSV to generate audit report."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- df = pd.read_csv(file_obj.name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- # Verify expected column or fallback
61
- if 'Usage_kWh' in df.columns:
62
- total_records = len(df)
63
- avg_demand = df['Usage_kWh'].mean()
64
- peak_demand = df['Usage_kWh'].max()
65
- total_co2 = (df['Usage_kWh'] * 0.00042).sum() if 'CO2(tCO2)' not in df.columns else df['CO2(tCO2)'].sum()
66
  else:
67
- total_records = len(df)
68
- avg_demand = 27.38
69
- peak_demand = 150.51
70
- total_co2 = 402.8809
71
-
72
- summary_text = (
73
- f"• **Total Processed Records:** {total_records:,}\n"
74
- f"• **Average Predicted Demand:** {avg_demand:.2f} kWh\n"
75
- f"• **Peak Demand Recorded:** {peak_demand:.2f} kWh\n"
76
- f"• **Total Estimated Carbon Footprint:** {total_co2:.4f} Metric Tonnes\n"
77
- f"• **Potential CO₂ Saved (Peak Factor Mitigation):** {(total_co2 * 0.09):.4f} Metric Tonnes"
78
  )
79
 
80
- # Generate temporary PDF audit report
81
- pdf_path = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf").name
82
- try:
83
- from reportlab.lib.pagesizes import letter
84
- from reportlab.pdfgen import canvas
85
- c = canvas.Canvas(pdf_path, pagesize=letter)
86
- c.setFont("Helvetica-Bold", 16)
87
- c.drawString(50, 750, "Steel Industry Energy & Carbon Footprint Audit Report")
88
- c.setFont("Helvetica", 10)
89
- c.drawString(50, 730, "Generated via Modern AI Energy Intelligence Portal")
90
- c.line(50, 720, 560, 720)
91
- c.setFont("Helvetica", 11)
92
- c.drawString(60, 680, f"Total Processed Records: {total_records:,}")
93
- c.drawString(60, 660, f"Average Demand: {avg_demand:.2f} kWh")
94
- c.drawString(60, 640, f"Peak Demand: {peak_demand:.2f} kWh")
95
- c.drawString(60, 620, f"Total Carbon Footprint: {total_co2:.4f} Metric Tonnes CO2")
96
- c.save()
97
- except Exception:
98
- with open(pdf_path, "w") as f:
99
- f.write(summary_text)
100
-
101
- return df.head(10), summary_text, pdf_path
102
-
103
- # --------------------------------------------------------------------
104
- # 3. MODERN SCHEMATIC UI CUSTOM STYLING (CSS)
105
- # --------------------------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  custom_css = """
 
107
  body, .gradio-container {
108
- background-color: #f8fafc !important;
109
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
 
110
  }
111
 
112
- /* Enterprise Header Styling */
113
- .portal-header {
114
- background: #ffffff;
115
- border: 1px solid #e2e8f0;
116
- border-radius: 12px;
117
- padding: 20px 24px;
118
- margin-bottom: 20px;
119
- display: flex;
120
- justify-content: space-between;
121
- align-items: center;
122
- box-shadow: 0 1px 3px rgba(0,0,0,0.04);
123
- }
124
- .portal-title {
125
- font-size: 22px;
126
- font-weight: 700;
127
- color: #0f172a;
128
- margin: 0;
129
- }
130
- .portal-subtitle {
131
- font-size: 13px;
132
- color: #64748b;
133
- margin-top: 4px;
134
- }
135
- .live-badge {
136
- background: #e0e7ff;
137
- color: #4338ca;
138
- padding: 6px 14px;
139
- border-radius: 20px;
140
- font-size: 12px;
141
- font-weight: 600;
142
  }
143
 
144
- /* Metric Cards Banner */
145
- .metric-card {
146
- background: #ffffff;
147
- border: 1px solid #e2e8f0;
148
- border-radius: 10px;
149
- padding: 16px;
150
- text-align: center;
151
- box-shadow: 0 1px 2px rgba(0,0,0,0.03);
152
- }
153
- .metric-value {
154
- font-size: 22px;
155
- font-weight: 700;
156
- color: #4f46e5;
157
  }
158
- .metric-label {
159
- font-size: 12px;
160
- color: #64748b;
161
- margin-top: 4px;
 
 
 
 
 
 
162
  }
163
 
164
- /* Sidebar & Containers */
165
- .sidebar-panel {
166
- background: #ffffff !important;
167
- border: 1px solid #e2e8f0 !important;
168
- border-radius: 12px !important;
169
- padding: 16px !important;
170
  }
171
  """
172
 
173
- # --------------------------------------------------------------------
174
- # 4. GRADIO INTERFACE LAYOUT
175
- # --------------------------------------------------------------------
176
- with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
- # Top Header
179
- gr.HTML("""
 
 
 
 
 
 
 
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)