-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlitplot.py
More file actions
398 lines (315 loc) Β· 12.9 KB
/
streamlitplot.py
File metadata and controls
398 lines (315 loc) Β· 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime
import time
import json
# Import your main classes (assuming they're in production_twin.py)
# from production_twin import ProductionLine, IntelligentAnalyzer
# For this demo, we'll include simplified versions here
# You can import from your main file once it's saved
st.set_page_config(
page_title="Production Line Digital Twin",
page_icon="π",
layout="wide"
)
# Initialize session state
if 'production_line' not in st.session_state:
st.session_state.production_line = None
st.session_state.analyzer = None
st.session_state.simulation_running = False
def main():
st.title("π AI-Powered Production Line Digital Twin")
st.markdown("*Intelligent Manufacturing Monitoring & Analysis*")
# Sidebar controls
with st.sidebar:
st.header("βοΈ Control Panel")
# Simulation controls
num_machines = st.slider("Number of Machines", 3, 10, 5)
simulation_duration = st.slider("Simulation Duration", 10, 200, 50)
if st.button("π Start New Simulation", type="primary"):
with st.spinner("Initializing production line..."):
# Import here to avoid issues if file doesn't exist yet
try:
from production_twin import ProductionLine, IntelligentAnalyzer
st.session_state.production_line = ProductionLine(num_machines=num_machines)
st.session_state.analyzer = IntelligentAnalyzer(st.session_state.production_line)
# Run simulation
st.session_state.production_line.start_production(duration=simulation_duration)
st.session_state.simulation_running = True
st.success("β
Simulation completed!")
st.rerun()
except ImportError:
st.error("Please make sure production_twin.py is in the same directory!")
except Exception as e:
st.error(f"Error: {str(e)}")
if st.button("π Refresh Data"):
if st.session_state.production_line:
st.rerun()
# Main content
if not st.session_state.simulation_running:
st.info("π Start a simulation using the control panel to begin monitoring!")
# Show demo info
st.subheader("π― Project Features")
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
**π€ Intelligent Analysis**
- Real-time anomaly detection
- Predictive maintenance alerts
- Performance optimization suggestions
""")
with col2:
st.markdown("""
**π Advanced Monitoring**
- Multi-machine dashboard
- Historical trend analysis
- Quality control metrics
""")
with col3:
st.markdown("""
**π¬ Natural Language Interface**
- Ask questions in plain English
- Get detailed explanations
- Interactive troubleshooting
""")
return
# Dashboard tabs
tab1, tab2, tab3, tab4 = st.tabs(["π Dashboard", "π€ AI Assistant", "π Analytics", "π§ Maintenance"])
with tab1:
show_dashboard()
with tab2:
show_ai_assistant()
with tab3:
show_analytics()
with tab4:
show_maintenance()
def show_dashboard():
st.header("π Real-Time Production Dashboard")
if not st.session_state.production_line:
st.warning("No simulation running!")
return
# Get current status
status = st.session_state.production_line.get_current_status()
analysis = st.session_state.production_line.analyze_performance()
# Key metrics row
col1, col2, col3, col4 = st.columns(4)
with col1:
total_production = analysis["overview"]["total_production"]
st.metric("Total Production", f"{total_production:,}", delta="units")
with col2:
avg_efficiency = analysis["overview"]["average_efficiency"]
st.metric("Average Efficiency", avg_efficiency, delta=None)
with col3:
avg_quality = analysis["overview"]["average_quality"]
st.metric("Average Quality", avg_quality, delta=None)
with col4:
issues = analysis["overview"]["machines_with_issues"]
st.metric("Machines with Issues", issues, delta=None)
st.divider()
# Machine status grid
st.subheader("π Machine Status Overview")
machines_data = []
for machine_id, machine_status in status["machines"].items():
machines_data.append({
"Machine": machine_id,
"Status": machine_status["status"],
"Efficiency": machine_status["efficiency"],
"Temperature": machine_status["temperature"],
"Quality": machine_status["quality_score"],
"Output": machine_status["output_count"]
})
df_machines = pd.DataFrame(machines_data)
# Color-code the status
def style_status(val):
color = 'green' if val == 'running' else 'red'
return f'color: {color}'
styled_df = df_machines.style.applymap(style_status, subset=['Status'])
st.dataframe(styled_df, use_container_width=True)
# Efficiency chart
col1, col2 = st.columns(2)
with col1:
fig_efficiency = px.bar(
df_machines,
x="Machine",
y="Efficiency",
title="Machine Efficiency Comparison",
color="Efficiency",
color_continuous_scale="RdYlGn"
)
fig_efficiency.update_layout(showlegend=False)
st.plotly_chart(fig_efficiency, use_container_width=True)
with col2:
fig_temp = px.bar(
df_machines,
x="Machine",
y="Temperature",
title="Temperature Monitoring",
color="Temperature",
color_continuous_scale="Reds"
)
fig_temp.update_layout(showlegend=False)
st.plotly_chart(fig_temp, use_container_width=True)
def show_ai_assistant():
st.header("π€ AI Production Assistant")
st.markdown("*Ask me anything about your production line!*")
if not st.session_state.analyzer:
st.warning("No simulation running!")
return
# AI Insights
with st.expander("π‘ Current AI Insights", expanded=True):
insights = st.session_state.analyzer.generate_insights()
for insight in insights:
st.markdown(f"β’ {insight}")
st.divider()
# Question & Answer Interface
st.subheader("π¬ Ask the AI Assistant")
# Pre-defined quick questions
st.markdown("**Quick Questions:**")
col1, col2, col3 = st.columns(3)
with col1:
if st.button("What's the current efficiency?"):
answer = st.session_state.analyzer.answer_question("What's the current efficiency?")
st.info(answer)
with col2:
if st.button("Any temperature issues?"):
answer = st.session_state.analyzer.answer_question("Are there any temperature problems?")
st.info(answer)
with col3:
if st.button("How's the quality?"):
answer = st.session_state.analyzer.answer_question("How is the quality?")
st.info(answer)
# Custom question input
st.markdown("**Ask a Custom Question:**")
user_question = st.text_input("Type your question here...")
if st.button("Get Answer") and user_question:
with st.spinner("AI is analyzing..."):
answer = st.session_state.analyzer.answer_question(user_question)
st.success(f"π€ **AI Response:** {answer}")
# Chat history (simplified)
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if user_question and st.button("πΎ Save to Chat History"):
answer = st.session_state.analyzer.answer_question(user_question)
st.session_state.chat_history.append({
"question": user_question,
"answer": answer,
"timestamp": datetime.now().strftime("%H:%M:%S")
})
st.rerun()
if st.session_state.chat_history:
st.subheader("π Chat History")
for i, chat in enumerate(reversed(st.session_state.chat_history[-5:])): # Show last 5
with st.expander(f"[{chat['timestamp']}] {chat['question'][:50]}..."):
st.markdown(f"**Q:** {chat['question']}")
st.markdown(f"**A:** {chat['answer']}")
def show_analytics():
st.header("π Advanced Analytics")
if not st.session_state.production_line:
st.warning("No simulation running!")
return
# Get metrics dataframe
df = st.session_state.production_line.get_metrics_dataframe()
if df.empty:
st.info("No metrics data available yet.")
return
# Time series charts
st.subheader("β±οΈ Performance Over Time")
# Convert timestamp to datetime if it's not already
if 'timestamp' in df.columns:
df['timestamp'] = pd.to_datetime(df['timestamp'])
col1, col2 = st.columns(2)
with col1:
fig_efficiency_time = px.line(
df,
x='timestamp',
y='efficiency',
color='machine_id',
title='Efficiency Trends Over Time'
)
st.plotly_chart(fig_efficiency_time, use_container_width=True)
with col2:
fig_quality_time = px.line(
df,
x='timestamp',
y='quality_score',
color='machine_id',
title='Quality Score Trends'
)
st.plotly_chart(fig_quality_time, use_container_width=True)
# Correlation analysis
st.subheader("π Performance Correlations")
numeric_cols = ['efficiency', 'temperature', 'vibration', 'quality_score']
correlation_matrix = df[numeric_cols].corr()
fig_corr = px.imshow(
correlation_matrix,
title="Correlation Matrix: Performance Metrics",
color_continuous_scale="RdBu"
)
st.plotly_chart(fig_corr, use_container_width=True)
# Statistical summary
st.subheader("π Statistical Summary")
st.dataframe(df[numeric_cols].describe(), use_container_width=True)
def show_maintenance():
st.header("π§ Predictive Maintenance")
if not st.session_state.production_line:
st.warning("No simulation running!")
return
analysis = st.session_state.production_line.analyze_performance()
# Maintenance alerts
st.subheader("β οΈ Maintenance Alerts")
col1, col2 = st.columns(2)
with col1:
st.markdown("**π‘οΈ Temperature Alerts**")
temp_alerts = analysis["trends"]["temperature_alerts"]
if temp_alerts:
for machine in temp_alerts:
st.error(f"π₯ {machine}: Overheating detected!")
else:
st.success("β
All temperatures normal")
with col2:
st.markdown("**π§ Vibration Alerts**")
vib_alerts = analysis["trends"]["vibration_alerts"]
if vib_alerts:
for machine in vib_alerts:
st.warning(f"β‘ {machine}: High vibration!")
else:
st.success("β
All vibrations normal")
# Maintenance schedule suggestions
st.subheader("π
Suggested Maintenance Schedule")
maintenance_suggestions = []
for machine_id, perf in analysis["machine_performance"].items():
efficiency = float(perf["current_efficiency"].replace("%", ""))
temp = float(perf["current_temperature"].replace("Β°C", ""))
priority = "Low"
action = "Regular inspection"
if efficiency < 80:
priority = "High"
action = "Immediate maintenance required"
elif temp > 50:
priority = "Medium"
action = "Cooling system check"
maintenance_suggestions.append({
"Machine": machine_id,
"Priority": priority,
"Action": action,
"Current Efficiency": perf["current_efficiency"],
"Status": perf["status"]
})
df_maintenance = pd.DataFrame(maintenance_suggestions)
# Color code by priority
def highlight_priority(val):
if val == "High":
return "background-color: #ffcccc"
elif val == "Medium":
return "background-color: #ffffcc"
else:
return "background-color: #ccffcc"
styled_maintenance = df_maintenance.style.applymap(
highlight_priority,
subset=['Priority']
)
st.dataframe(styled_maintenance, use_container_width=True)
if __name__ == "__main__":
main()