bhagwandas commited on
Commit
9cf3310
Β·
verified Β·
1 Parent(s): 5a9c5f9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -8
app.py CHANGED
@@ -1,11 +1,11 @@
1
- # app.py - FactoryGPT 5.0: Role-Differentiated Technical Assistant
2
-
3
  import streamlit as st
4
  import pandas as pd
5
  import numpy as np
 
6
  from sentence_transformers import SentenceTransformer
7
  from transformers import pipeline
8
  from sklearn.ensemble import IsolationForest
 
9
 
10
  # App Config
11
  st.set_page_config(
@@ -23,7 +23,8 @@ st.markdown("""
23
  color: #f0f0f0;
24
  }
25
  .stTextInput>div>div>input,
26
- .stSelectbox>div>div>div>div {
 
27
  background-color: #1a1c23;
28
  color: #fff;
29
  }
@@ -57,7 +58,7 @@ if uploaded_file:
57
  st.markdown("### πŸ“Š Sensor Data Snapshot")
58
  st.dataframe(df.head(), use_container_width=True)
59
 
60
- # Vector Chunking for RAG
61
  def convert_to_chunks(df):
62
  return [f"[Entry {i}] " + ", ".join([f"{col}: {row[col]:.2f}" for col in numeric_cols]) for i, row in df.iterrows()]
63
 
@@ -67,15 +68,82 @@ if uploaded_file:
67
  st.session_state.chunks = chunks
68
  st.session_state.embeddings = embeddings
69
 
70
- # Predictive Anomaly Detection
71
- st.markdown("### πŸ”Ž Machine Health Assessment")
72
  iso = IsolationForest(contamination=0.02)
73
  labels = iso.fit_predict(df[numeric_cols])
74
  df['status'] = ['❌ Fault Detected' if x == -1 else 'βœ… Healthy' for x in labels]
75
  df['maintenance_flag'] = ['πŸ”§ Inspect Required' if x == -1 else '🟒 Stable' for x in labels]
 
 
76
  st.dataframe(df[['status', 'maintenance_flag'] + numeric_cols].head(), use_container_width=True)
77
 
78
- # Role-based Response Logic
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  st.markdown("### πŸ’¬ Technical Assistant by Role")
80
  roles = {
81
  "Operator": {
@@ -114,7 +182,7 @@ if uploaded_file:
114
  top_idxs = np.argsort(sims)[-5:][::-1]
115
  context = "\n".join([st.session_state.chunks[i] for i in top_idxs])
116
 
117
- # Build Prompt
118
  system_instruction = (
119
  f"ROLE: {role}\n"
120
  f"RESPONSIBILITIES: {roles[role]['description']}\n"
 
 
 
1
  import streamlit as st
2
  import pandas as pd
3
  import numpy as np
4
+ import matplotlib.pyplot as plt
5
  from sentence_transformers import SentenceTransformer
6
  from transformers import pipeline
7
  from sklearn.ensemble import IsolationForest
8
+ from io import BytesIO
9
 
10
  # App Config
11
  st.set_page_config(
 
23
  color: #f0f0f0;
24
  }
25
  .stTextInput>div>div>input,
26
+ .stSelectbox>div>div>div>div,
27
+ .stFileUploader>div>div {
28
  background-color: #1a1c23;
29
  color: #fff;
30
  }
 
58
  st.markdown("### πŸ“Š Sensor Data Snapshot")
59
  st.dataframe(df.head(), use_container_width=True)
60
 
61
+ # Run Vector Chunking
62
  def convert_to_chunks(df):
63
  return [f"[Entry {i}] " + ", ".join([f"{col}: {row[col]:.2f}" for col in numeric_cols]) for i, row in df.iterrows()]
64
 
 
68
  st.session_state.chunks = chunks
69
  st.session_state.embeddings = embeddings
70
 
71
+ # Detect Anomalies
 
72
  iso = IsolationForest(contamination=0.02)
73
  labels = iso.fit_predict(df[numeric_cols])
74
  df['status'] = ['❌ Fault Detected' if x == -1 else 'βœ… Healthy' for x in labels]
75
  df['maintenance_flag'] = ['πŸ”§ Inspect Required' if x == -1 else '🟒 Stable' for x in labels]
76
+
77
+ st.markdown("### πŸ”Ž Machine Health Assessment")
78
  st.dataframe(df[['status', 'maintenance_flag'] + numeric_cols].head(), use_container_width=True)
79
 
80
+ # Health Overview Chart
81
+ st.markdown("### πŸ“ˆ Machine Health Summary")
82
+ status_counts = df['status'].value_counts()
83
+ fig1, ax1 = plt.subplots()
84
+ ax1.bar(status_counts.index, status_counts.values, color=["red", "green"])
85
+ ax1.set_title("Machine Health Status")
86
+ ax1.set_ylabel("Occurrences")
87
+ ax1.set_facecolor("#0f1117")
88
+ ax1.tick_params(colors='white')
89
+ ax1.title.set_color('white')
90
+ ax1.yaxis.label.set_color('white')
91
+ for spine in ax1.spines.values():
92
+ spine.set_edgecolor('white')
93
+ st.pyplot(fig1)
94
+
95
+ # Parameter Trend Chart
96
+ st.markdown("### πŸ“‰ Sensor Parameter Trend")
97
+ time_col = st.selectbox("πŸ•’ Select Time Column (optional)", ["None"] + list(df.columns))
98
+ param = st.selectbox("πŸ“Œ Choose a Parameter to Visualize", numeric_cols)
99
+
100
+ if time_col != "None":
101
+ df = df.sort_values(by=time_col)
102
+
103
+ fig2, ax2 = plt.subplots()
104
+ x_vals = df[time_col] if time_col != "None" else df.index
105
+ ax2.plot(x_vals, df[param], label=param, color="skyblue")
106
+ anomaly_x = x_vals[df['status'] == '❌ Fault Detected']
107
+ anomaly_y = df[param][df['status'] == '❌ Fault Detected']
108
+ ax2.scatter(anomaly_x, anomaly_y, color='red', label='Fault Detected', zorder=5)
109
+ ax2.set_title(f"{param} Over Time")
110
+ ax2.set_xlabel("Time" if time_col != "None" else "Index")
111
+ ax2.set_ylabel(param)
112
+ ax2.legend()
113
+ ax2.set_facecolor("#0f1117")
114
+ ax2.tick_params(colors='white')
115
+ ax2.title.set_color('white')
116
+ ax2.xaxis.label.set_color('white')
117
+ ax2.yaxis.label.set_color('white')
118
+ for spine in ax2.spines.values():
119
+ spine.set_edgecolor('white')
120
+ st.pyplot(fig2)
121
+
122
+ # Parameter List
123
+ st.markdown("### πŸ§ͺ Parameters Monitored")
124
+ st.markdown(", ".join(numeric_cols))
125
+
126
+ # Export Anomalies
127
+ st.markdown("### πŸ“€ Export Flagged Anomalies")
128
+ anomalies_df = df[df['status'] == '❌ Fault Detected']
129
+ buffer = BytesIO()
130
+ anomalies_df.to_csv(buffer, index=False)
131
+ st.download_button(
132
+ label="⬇️ Download Fault Records",
133
+ data=buffer.getvalue(),
134
+ file_name="fault_records.csv",
135
+ mime="text/csv"
136
+ )
137
+
138
+ # Fault Correlation if Metadata Exists
139
+ st.markdown("### 🏷️ Fault Distribution by Machine/Component")
140
+ metadata_cols = [col for col in df.columns if 'machine' in col.lower() or 'component' in col.lower()]
141
+ for col in metadata_cols:
142
+ st.markdown(f"**{col.capitalize()} – Fault Frequency**")
143
+ fault_counts = df[df['status'] == '❌ Fault Detected'][col].value_counts()
144
+ st.bar_chart(fault_counts)
145
+
146
+ # Role-based Technical Assistant
147
  st.markdown("### πŸ’¬ Technical Assistant by Role")
148
  roles = {
149
  "Operator": {
 
182
  top_idxs = np.argsort(sims)[-5:][::-1]
183
  context = "\n".join([st.session_state.chunks[i] for i in top_idxs])
184
 
185
+ # Prompt Assembly
186
  system_instruction = (
187
  f"ROLE: {role}\n"
188
  f"RESPONSIBILITIES: {roles[role]['description']}\n"