entropy25 commited on
Commit
730af87
Β·
verified Β·
1 Parent(s): dec5562

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +414 -0
app.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pandas as pd
3
+ import numpy as np
4
+ import plotly.graph_objects as go
5
+ import plotly.express as px
6
+ from datetime import datetime, timedelta
7
+ import io
8
+ import base64
9
+ from reportlab.lib.pagesizes import letter
10
+ from reportlab.pdfgen import canvas
11
+ from reportlab.lib.utils import ImageReader
12
+ import random
13
+
14
+ # Global CSS for styling
15
+ css = """
16
+ .gradio-container {
17
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
18
+ font-family: 'Segoe UI', sans-serif;
19
+ }
20
+
21
+ .gr-button {
22
+ background: linear-gradient(135deg, #667eea, #764ba2) !important;
23
+ border: none !important;
24
+ border-radius: 10px !important;
25
+ box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3) !important;
26
+ transition: all 0.3s ease !important;
27
+ }
28
+
29
+ .gr-button:hover {
30
+ transform: translateY(-2px) !important;
31
+ box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4) !important;
32
+ }
33
+
34
+ .gr-panel {
35
+ background: rgba(255, 255, 255, 0.95) !important;
36
+ backdrop-filter: blur(10px) !important;
37
+ border-radius: 20px !important;
38
+ border: 1px solid rgba(255, 255, 255, 0.3) !important;
39
+ }
40
+ """
41
+
42
+ # Data generation functions
43
+ def generate_sensor_data():
44
+ """Generate simulated sensor data for predictive maintenance"""
45
+ np.random.seed(42)
46
+ timestamps = pd.date_range(start=datetime.now() - timedelta(hours=200), periods=200, freq='H')
47
+
48
+ # Generate sensor data with anomalies
49
+ vibration = 2 + np.sin(np.arange(200) * 0.1) * 0.5 + np.random.normal(0, 0.2, 200)
50
+ temperature = 65 + np.sin(np.arange(200) * 0.05) * 10 + np.random.normal(0, 3, 200)
51
+ pressure = 85 + np.cos(np.arange(200) * 0.08) * 5 + np.random.normal(0, 2, 200)
52
+
53
+ # Add anomalies
54
+ vibration[150:160] += np.random.uniform(1, 3, 10)
55
+ temperature[150:160] += np.random.uniform(10, 20, 10)
56
+ pressure[180:] -= np.random.uniform(5, 15, 20)
57
+
58
+ df = pd.DataFrame({
59
+ 'timestamp': timestamps,
60
+ 'vibration': vibration,
61
+ 'temperature': temperature,
62
+ 'pressure': pressure
63
+ })
64
+
65
+ return df
66
+
67
+ def predictive_maintenance_analysis():
68
+ """Run predictive maintenance analysis"""
69
+ df = generate_sensor_data()
70
+
71
+ # Calculate anomaly scores
72
+ anomaly_scores = []
73
+ for i, row in df.iterrows():
74
+ score = abs(row['vibration'] - 2) * 0.3 + abs(row['temperature'] - 65) * 0.02
75
+ if 150 <= i < 160:
76
+ score += 0.5
77
+ if i >= 180:
78
+ score += 0.3
79
+ anomaly_scores.append(min(score, 1))
80
+
81
+ df['anomaly_score'] = anomaly_scores
82
+ df['failure_probability'] = np.minimum(np.array(anomaly_scores) * 1.2 + np.random.uniform(0, 0.1, len(anomaly_scores)), 1)
83
+
84
+ # Create visualization
85
+ fig = go.Figure()
86
+
87
+ fig.add_trace(go.Scatter(
88
+ x=df['timestamp'], y=df['vibration'],
89
+ mode='lines', name='Vibration (mm/s)',
90
+ line=dict(color='#ff6b6b', width=2)
91
+ ))
92
+
93
+ fig.add_trace(go.Scatter(
94
+ x=df['timestamp'], y=df['temperature'],
95
+ mode='lines', name='Temperature (Β°C)',
96
+ line=dict(color='#4ecdc4', width=2),
97
+ yaxis='y2'
98
+ ))
99
+
100
+ fig.add_trace(go.Scatter(
101
+ x=df['timestamp'], y=df['failure_probability'],
102
+ mode='lines', name='Failure Probability',
103
+ line=dict(color='#feca57', width=3),
104
+ yaxis='y3'
105
+ ))
106
+
107
+ fig.update_layout(
108
+ title='Equipment Health Monitoring & Failure Prediction',
109
+ xaxis_title='Time',
110
+ yaxis=dict(title='Vibration (mm/s)', side='left'),
111
+ yaxis2=dict(title='Temperature (Β°C)', overlaying='y', side='right', position=0.95),
112
+ yaxis3=dict(title='Failure Probability', overlaying='y', side='right'),
113
+ height=500,
114
+ showlegend=True,
115
+ template='plotly_white'
116
+ )
117
+
118
+ # Generate metrics
119
+ anomalies_detected = sum(1 for score in anomaly_scores if score > 0.5)
120
+ max_risk = max(df['failure_probability']) * 100
121
+ maintenance_days = 5
122
+
123
+ summary = f"""
124
+ πŸ” **Analysis Results:**
125
+ - **Anomalies Detected:** {anomalies_detected}
126
+ - **Maximum Risk:** {max_risk:.1f}%
127
+ - **Recommended Maintenance:** {maintenance_days} days
128
+
129
+ ⚠️ **Alert:** Equipment vibration anomaly detected. Maintenance recommended within 5 days.
130
+ """
131
+
132
+ return fig, summary
133
+
134
+ def route_optimization():
135
+ """Simulate route optimization for work order dispatch"""
136
+ np.random.seed(42)
137
+
138
+ # Generate vehicles and tasks
139
+ vehicles = [
140
+ {'id': 'V001', 'lat': 22.3193, 'lng': 114.1694, 'capacity': 8},
141
+ {'id': 'V002', 'lat': 22.3093, 'lng': 114.1794, 'capacity': 6},
142
+ {'id': 'V003', 'lat': 22.3293, 'lng': 114.1594, 'capacity': 10}
143
+ ]
144
+
145
+ tasks = []
146
+ priorities = ['High', 'Medium', 'Low']
147
+ for i in range(1, 9):
148
+ tasks.append({
149
+ 'id': f'T{i:03d}',
150
+ 'lat': 22.3193 + (np.random.random() - 0.5) * 0.1,
151
+ 'lng': 114.1694 + (np.random.random() - 0.5) * 0.1,
152
+ 'priority': np.random.choice(priorities),
153
+ 'duration': np.random.randint(1, 5),
154
+ 'description': f'Pipeline Cleaning Task {i}'
155
+ })
156
+
157
+ # Simulate optimization results
158
+ optimized_routes = [
159
+ {'vehicle': 'V001', 'tasks': ['T001', 'T003', 'T005'], 'distance': 24.5, 'time': '3.2h'},
160
+ {'vehicle': 'V002', 'tasks': ['T002', 'T004', 'T006'], 'distance': 18.7, 'time': '2.8h'},
161
+ {'vehicle': 'V003', 'tasks': ['T007', 'T008'], 'distance': 15.2, 'time': '2.1h'}
162
+ ]
163
+
164
+ # Create map visualization
165
+ fig = go.Figure()
166
+
167
+ # Add vehicles
168
+ for i, vehicle in enumerate(vehicles):
169
+ fig.add_trace(go.Scattermapbox(
170
+ lat=[vehicle['lat']],
171
+ lon=[vehicle['lng']],
172
+ mode='markers',
173
+ marker=dict(size=15, color=['red', 'blue', 'green'][i]),
174
+ text=f"Vehicle {vehicle['id']}",
175
+ name=vehicle['id']
176
+ ))
177
+
178
+ # Add tasks
179
+ task_lats = [task['lat'] for task in tasks]
180
+ task_lngs = [task['lng'] for task in tasks]
181
+ task_texts = [f"{task['id']}: {task['description']}" for task in tasks]
182
+
183
+ fig.add_trace(go.Scattermapbox(
184
+ lat=task_lats,
185
+ lon=task_lngs,
186
+ mode='markers',
187
+ marker=dict(size=10, color='orange'),
188
+ text=task_texts,
189
+ name='Tasks'
190
+ ))
191
+
192
+ fig.update_layout(
193
+ mapbox=dict(
194
+ style="open-street-map",
195
+ center=dict(lat=22.3193, lon=114.1694),
196
+ zoom=12
197
+ ),
198
+ height=500,
199
+ title="Optimized Route Dispatch Map"
200
+ )
201
+
202
+ # Generate summary
203
+ total_distance = sum(route['distance'] for route in optimized_routes)
204
+ total_time = sum(float(route['time'][:-1]) for route in optimized_routes)
205
+ efficiency_improvement = 35
206
+
207
+ summary = f"""
208
+ 🎯 **Optimization Results:**
209
+ - **Total Distance:** {total_distance} km
210
+ - **Total Time:** {total_time:.1f} hours
211
+ - **Efficiency Improvement:** {efficiency_improvement}%
212
+
213
+ πŸ“‹ **Route Assignments:**
214
+ """
215
+
216
+ for route in optimized_routes:
217
+ summary += f"\n- **{route['vehicle']}**: {' β†’ '.join(route['tasks'])} ({route['distance']}km, {route['time']})"
218
+
219
+ return fig, summary
220
+
221
+ def quality_analysis():
222
+ """Run quality assurance monitoring and analysis"""
223
+ np.random.seed(42)
224
+
225
+ # Generate quality data
226
+ pipelines = []
227
+ for i in range(1, 7):
228
+ before_cleaning = np.random.uniform(10, 25) # 10-25% residual
229
+ after_cleaning = np.random.uniform(0.5, 3.5) # 0.5-3.5% residual
230
+ flow_recovery = np.random.uniform(85, 97) # 85-97% flow recovery
231
+
232
+ status = 'Pass' if after_cleaning < 2 and flow_recovery > 90 else 'Fail'
233
+
234
+ pipelines.append({
235
+ 'id': f'P{i:03d}',
236
+ 'before_cleaning': before_cleaning,
237
+ 'after_cleaning': after_cleaning,
238
+ 'flow_recovery': flow_recovery,
239
+ 'status': status
240
+ })
241
+
242
+ df = pd.DataFrame(pipelines)
243
+
244
+ # Create comparison chart
245
+ fig = go.Figure()
246
+
247
+ fig.add_trace(go.Bar(
248
+ x=df['id'],
249
+ y=df['before_cleaning'],
250
+ name='Before Cleaning (%)',
251
+ marker_color='#e17055'
252
+ ))
253
+
254
+ fig.add_trace(go.Bar(
255
+ x=df['id'],
256
+ y=df['after_cleaning'],
257
+ name='After Cleaning (%)',
258
+ marker_color='#00b894'
259
+ ))
260
+
261
+ fig.update_layout(
262
+ title='Pipeline Cleaning Effectiveness Comparison',
263
+ xaxis_title='Pipeline ID',
264
+ yaxis_title='Residual Rate (%)',
265
+ barmode='group',
266
+ height=400,
267
+ template='plotly_white'
268
+ )
269
+
270
+ # Calculate metrics
271
+ passed = len(df[df['status'] == 'Pass'])
272
+ failed = len(df) - passed
273
+ pass_rate = (passed / len(df)) * 100
274
+
275
+ summary = f"""
276
+ βœ… **Quality Analysis Results:**
277
+ - **Passed:** {passed} pipelines
278
+ - **Failed:** {failed} pipelines
279
+ - **Pass Rate:** {pass_rate:.1f}%
280
+
281
+ πŸ“Š **Detailed Results:**
282
+ """
283
+
284
+ for _, pipeline in df.iterrows():
285
+ status_emoji = "βœ…" if pipeline['status'] == 'Pass' else "❌"
286
+ summary += f"\n{status_emoji} **{pipeline['id']}**: {pipeline['status']} (Residual: {pipeline['after_cleaning']:.1f}%, Flow: {pipeline['flow_recovery']:.1f}%)"
287
+
288
+ return fig, summary, df
289
+
290
+ def generate_pdf_report():
291
+ """Generate PDF quality report"""
292
+ _, _, df = quality_analysis()
293
+
294
+ # Create PDF in memory
295
+ buffer = io.BytesIO()
296
+ p = canvas.Canvas(buffer, pagesize=letter)
297
+
298
+ # Title
299
+ p.setFont("Helvetica-Bold", 20)
300
+ p.drawString(50, 750, "Pipeline Cleaning Quality Report")
301
+
302
+ # Basic info
303
+ p.setFont("Helvetica", 12)
304
+ p.drawString(50, 720, f"Report Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
305
+ p.drawString(50, 700, f"Total Pipelines Tested: {len(df)}")
306
+
307
+ # Statistics
308
+ passed = len(df[df['status'] == 'Pass'])
309
+ pass_rate = (passed / len(df)) * 100
310
+ p.drawString(50, 680, f"Pass Rate: {pass_rate:.1f}%")
311
+
312
+ # Detailed results
313
+ p.setFont("Helvetica-Bold", 14)
314
+ p.drawString(50, 650, "Detailed Test Results:")
315
+
316
+ p.setFont("Helvetica", 10)
317
+ y_pos = 630
318
+ for _, pipeline in df.iterrows():
319
+ result_text = f"{pipeline['id']}: {pipeline['status']} - Residual: {pipeline['after_cleaning']:.1f}%, Flow Recovery: {pipeline['flow_recovery']:.1f}%"
320
+ p.drawString(60, y_pos, result_text)
321
+ y_pos -= 20
322
+
323
+ p.save()
324
+ buffer.seek(0)
325
+
326
+ return buffer.getvalue()
327
+
328
+ # Create Gradio interface
329
+ def create_interface():
330
+ with gr.Blocks(css=css, title="AI Engine - Smart Maintenance System") as demo:
331
+ gr.HTML("""
332
+ <div style="text-align: center; padding: 30px; background: rgba(255,255,255,0.1); border-radius: 20px; margin-bottom: 30px;">
333
+ <h1 style="color: white; font-size: 2.5em; margin-bottom: 10px; text-shadow: 2px 2px 4px rgba(0,0,0,0.3);">
334
+ πŸ€– AI Engine - Smart Maintenance System
335
+ </h1>
336
+ <p style="color: rgba(255,255,255,0.9); font-size: 1.2em;">
337
+ AI-Powered Pipeline Cleaning & Maintenance Solution
338
+ </p>
339
+ </div>
340
+ """)
341
+
342
+ with gr.Tabs():
343
+ # Predictive Maintenance Tab
344
+ with gr.TabItem("πŸ”§ Predictive Maintenance"):
345
+ gr.HTML("<h3>πŸ” LSTM-based Anomaly Detection & Failure Prediction</h3>")
346
+
347
+ with gr.Row():
348
+ with gr.Column():
349
+ predict_btn = gr.Button("πŸš€ Run Predictive Analysis", variant="primary")
350
+ predict_summary = gr.Markdown()
351
+
352
+ with gr.Column():
353
+ predict_plot = gr.Plot()
354
+
355
+ predict_btn.click(
356
+ predictive_maintenance_analysis,
357
+ outputs=[predict_plot, predict_summary]
358
+ )
359
+
360
+ # Route Optimization Tab
361
+ with gr.TabItem("πŸš› Route Optimization"):
362
+ gr.HTML("<h3>🎯 OR-Tools Vehicle Routing Problem (VRP) Solver</h3>")
363
+
364
+ with gr.Row():
365
+ with gr.Column():
366
+ route_btn = gr.Button("πŸ—ΊοΈ Optimize Routes", variant="primary")
367
+ route_summary = gr.Markdown()
368
+
369
+ with gr.Column():
370
+ route_plot = gr.Plot()
371
+
372
+ route_btn.click(
373
+ route_optimization,
374
+ outputs=[route_plot, route_summary]
375
+ )
376
+
377
+ # Quality Assurance Tab
378
+ with gr.TabItem("πŸ“Š Quality Assurance"):
379
+ gr.HTML("<h3>βœ… Automated Quality Monitoring & Reporting</h3>")
380
+
381
+ with gr.Row():
382
+ with gr.Column():
383
+ quality_btn = gr.Button("πŸ“‹ Run Quality Analysis", variant="primary")
384
+ pdf_btn = gr.Button("πŸ“„ Generate PDF Report", variant="secondary")
385
+ quality_summary = gr.Markdown()
386
+ pdf_output = gr.File(label="Download Report")
387
+
388
+ with gr.Column():
389
+ quality_plot = gr.Plot()
390
+
391
+ quality_btn.click(
392
+ lambda: quality_analysis()[:2],
393
+ outputs=[quality_plot, quality_summary]
394
+ )
395
+
396
+ pdf_btn.click(
397
+ generate_pdf_report,
398
+ outputs=[pdf_output]
399
+ )
400
+
401
+ gr.HTML("""
402
+ <div style="text-align: center; margin-top: 30px; padding: 20px; background: rgba(255,255,255,0.1); border-radius: 15px;">
403
+ <p style="color: white;">
404
+ πŸš€ <strong>AI Engine Demo</strong> | Powered by Machine Learning & Optimization Algorithms
405
+ </p>
406
+ </div>
407
+ """)
408
+
409
+ return demo
410
+
411
+ # Launch the application
412
+ if __name__ == "__main__":
413
+ demo = create_interface()
414
+ demo.launch(share=True)