Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,223 +1,100 @@
|
|
1 |
import streamlit as st
|
2 |
import pandas as pd
|
3 |
-
import numpy as np
|
4 |
import matplotlib.pyplot as plt
|
5 |
-
|
6 |
-
from transformers import pipeline
|
7 |
from sklearn.ensemble import IsolationForest
|
8 |
-
from
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
)
|
16 |
-
|
17 |
-
|
18 |
-
EMBED_MODEL = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
|
19 |
-
GEN_MODEL = pipeline('text2text-generation', model='google/flan-t5-base')
|
20 |
-
|
21 |
-
# Optional: Units per parameter
|
22 |
-
unit_map = {
|
23 |
-
"temperature": "Β°C",
|
24 |
-
"vibration": "mm/s",
|
25 |
-
"pressure": "bar",
|
26 |
-
"current": "A",
|
27 |
-
"voltage": "V",
|
28 |
-
"speed": "RPM"
|
29 |
-
}
|
30 |
-
|
31 |
-
# Style
|
32 |
-
st.markdown("""
|
33 |
-
<style>
|
34 |
-
html, body, [class*="css"] {
|
35 |
-
font-family: 'Segoe UI', sans-serif;
|
36 |
-
background-color: #0f1117;
|
37 |
-
color: #f0f0f0;
|
38 |
-
}
|
39 |
-
.card {
|
40 |
-
background-color: #1a1c23;
|
41 |
-
padding: 1rem;
|
42 |
-
border-radius: 10px;
|
43 |
-
margin-bottom: 1rem;
|
44 |
-
box-shadow: 0 0 8px rgba(88,166,255,0.2);
|
45 |
-
}
|
46 |
-
</style>
|
47 |
-
""", unsafe_allow_html=True)
|
48 |
-
|
49 |
-
# Header
|
50 |
-
st.markdown("""
|
51 |
-
<div style='text-align: center;'>
|
52 |
-
<h1 style='color: #58a6ff;'>π FactoryGPT 5.0 β Technical Maintenance Dashboard</h1>
|
53 |
-
<p style='color: #bbb;'>Anomaly Monitoring β’ Parameter Trends β’ Role-Based Intelligence</p>
|
54 |
-
<hr style='border-top: 2px solid #888;'>
|
55 |
-
</div>
|
56 |
-
""", unsafe_allow_html=True)
|
57 |
|
58 |
# File Upload
|
59 |
-
uploaded_file = st.
|
60 |
|
61 |
if uploaded_file:
|
62 |
df = pd.read_csv(uploaded_file)
|
63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
# Anomaly Detection
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
# Health Summary
|
82 |
-
col1, col2 = st.columns(2)
|
83 |
-
with col1:
|
84 |
-
st.markdown("### π§ Machine Health Summary")
|
85 |
-
status_counts = df['status'].value_counts()
|
86 |
-
fig1, ax1 = plt.subplots(figsize=(5, 4))
|
87 |
-
bars = ax1.bar(status_counts.index, status_counts.values, color=["red", "green"])
|
88 |
-
ax1.set_title("Detected Machine Health Conditions", fontsize=14)
|
89 |
-
ax1.set_ylabel("Record Count")
|
90 |
-
ax1.set_xlabel("Status")
|
91 |
-
ax1.set_facecolor("#0f1117")
|
92 |
-
ax1.tick_params(colors='white')
|
93 |
-
ax1.title.set_color('white')
|
94 |
-
ax1.xaxis.label.set_color('white')
|
95 |
-
ax1.yaxis.label.set_color('white')
|
96 |
-
for spine in ax1.spines.values():
|
97 |
-
spine.set_edgecolor('white')
|
98 |
-
for bar in bars:
|
99 |
-
height = bar.get_height()
|
100 |
-
ax1.annotate(f'{height:,}', xy=(bar.get_x() + bar.get_width()/2, height),
|
101 |
-
xytext=(0, 6), textcoords="offset points", ha='center', color='white')
|
102 |
-
st.pyplot(fig1)
|
103 |
-
|
104 |
-
with col2:
|
105 |
-
st.markdown("### π§ͺ Parameters Monitored")
|
106 |
-
st.markdown(f"""
|
107 |
-
<div class="card">
|
108 |
-
{' β’ '.join(numeric_cols)}
|
109 |
-
</div>
|
110 |
-
""", unsafe_allow_html=True)
|
111 |
-
|
112 |
-
# Trend Plot
|
113 |
-
st.markdown("### π Sensor Trend (with Fault Overlay)")
|
114 |
-
col3, col4 = st.columns(2)
|
115 |
-
time_col = col3.selectbox("π Time Column", ["None"] + list(df.columns))
|
116 |
-
trend_param = col4.selectbox("π Select Parameter", numeric_cols)
|
117 |
-
|
118 |
-
if time_col != "None":
|
119 |
-
df = df.sort_values(by=time_col)
|
120 |
-
|
121 |
-
x_vals = df[time_col] if time_col != "None" else df.index
|
122 |
-
y_vals = df[trend_param]
|
123 |
-
y_label = f"{trend_param} ({unit_map.get(trend_param.lower(), '')})"
|
124 |
-
|
125 |
-
fig2, ax2 = plt.subplots(figsize=(8, 4.5))
|
126 |
-
ax2.plot(x_vals, y_vals, label=trend_param, color="skyblue", linewidth=1.5)
|
127 |
-
ax2.scatter(
|
128 |
-
x_vals[df['status'] == 'β Fault Detected'],
|
129 |
-
y_vals[df['status'] == 'β Fault Detected'],
|
130 |
-
color='red', label='Fault Detected', zorder=5
|
131 |
-
)
|
132 |
-
ax2.set_title(f"{trend_param} Sensor Trend")
|
133 |
-
ax2.set_xlabel("Time" if time_col != "None" else "Index")
|
134 |
-
ax2.set_ylabel(y_label)
|
135 |
-
ax2.legend()
|
136 |
-
ax2.set_facecolor("#0f1117")
|
137 |
-
ax2.tick_params(colors='white')
|
138 |
-
ax2.title.set_color('white')
|
139 |
-
ax2.xaxis.label.set_color('white')
|
140 |
-
ax2.yaxis.label.set_color('white')
|
141 |
-
for spine in ax2.spines.values():
|
142 |
-
spine.set_edgecolor('white')
|
143 |
-
st.pyplot(fig2)
|
144 |
-
|
145 |
-
img_buffer = BytesIO()
|
146 |
-
fig2.savefig(img_buffer, format='png', bbox_inches="tight")
|
147 |
-
st.download_button("π· Download Trend Chart (PNG)", img_buffer.getvalue(), file_name="sensor_trend.png")
|
148 |
-
|
149 |
-
# Fault Rate Over Time
|
150 |
-
if time_col != "None":
|
151 |
-
st.markdown("### π Fault Rate Over Time")
|
152 |
-
df[time_col] = pd.to_datetime(df[time_col], errors='coerce')
|
153 |
-
df['fault_flag'] = df['status'].apply(lambda x: 1 if x == 'β Fault Detected' else 0)
|
154 |
-
freq = 'H' if (df[time_col].max() - df[time_col].min()).days <= 3 else 'D'
|
155 |
-
grouped = df.set_index(time_col)['fault_flag'].resample(freq).mean() * 100
|
156 |
-
|
157 |
-
fig3, ax3 = plt.subplots(figsize=(8, 4))
|
158 |
-
ax3.plot(grouped.index, grouped, color='orange', linewidth=2)
|
159 |
-
ax3.set_title("Fault Rate Over Time")
|
160 |
-
ax3.set_ylabel("Fault Rate (%)")
|
161 |
-
ax3.set_xlabel("Time")
|
162 |
-
ax3.set_facecolor("#0f1117")
|
163 |
-
ax3.tick_params(colors='white')
|
164 |
-
ax3.title.set_color('white')
|
165 |
-
ax3.yaxis.label.set_color('white')
|
166 |
-
ax3.xaxis.label.set_color('white')
|
167 |
-
for spine in ax3.spines.values():
|
168 |
-
spine.set_edgecolor('white')
|
169 |
-
st.pyplot(fig3)
|
170 |
-
|
171 |
-
# Export Faults
|
172 |
-
st.markdown("### π€ Export Anomalies")
|
173 |
-
fault_df = df[df['status'] == 'β Fault Detected']
|
174 |
-
buf = BytesIO()
|
175 |
-
fault_df.to_csv(buf, index=False)
|
176 |
-
st.download_button("β¬οΈ Download Fault Log", data=buf.getvalue(), file_name="faults.csv", mime="text/csv")
|
177 |
-
|
178 |
-
# Metadata correlation
|
179 |
-
st.markdown("### π·οΈ Fault Distribution by Machine/Component")
|
180 |
-
meta_cols = [c for c in df.columns if 'machine' in c.lower() or 'component' in c.lower()]
|
181 |
-
for col in meta_cols:
|
182 |
-
st.markdown(f"**{col} β Fault Frequency**")
|
183 |
-
st.bar_chart(df[df['status'] == 'β Fault Detected'][col].value_counts())
|
184 |
-
|
185 |
-
# Role Assistant
|
186 |
-
st.markdown("### π¬ Technical Assistant by Role")
|
187 |
-
roles = {
|
188 |
-
"Operator": {
|
189 |
-
"description": "Focus on equipment behavior. Spot abnormal patterns and guide simple actions.",
|
190 |
-
"style": "Explain simply. Emphasize safety and when to alert maintenance."
|
191 |
-
},
|
192 |
-
"Maintenance": {
|
193 |
-
"description": "Diagnose machine issues. Recommend parts to inspect or replace.",
|
194 |
-
"style": "Use technical language. Mention symptoms and sensor causes."
|
195 |
-
},
|
196 |
-
"Engineer": {
|
197 |
-
"description": "Analyze system behavior. Identify root causes or instability.",
|
198 |
-
"style": "Use RCA format. Discuss fault thresholds, control issues, and next steps."
|
199 |
-
}
|
200 |
-
}
|
201 |
-
|
202 |
-
role = st.selectbox("π€ Select your role", roles.keys())
|
203 |
-
question = st.text_input("π§ Ask a question")
|
204 |
|
205 |
if question:
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
221 |
|
222 |
else:
|
223 |
-
st.info("
|
|
|
1 |
import streamlit as st
|
2 |
import pandas as pd
|
|
|
3 |
import matplotlib.pyplot as plt
|
4 |
+
import seaborn as sns
|
|
|
5 |
from sklearn.ensemble import IsolationForest
|
6 |
+
from sklearn.preprocessing import StandardScaler
|
7 |
+
import openai
|
8 |
+
import os
|
9 |
+
|
10 |
+
# Set your OpenAI key here or use Hugging Face Secrets Manager
|
11 |
+
openai.api_key = os.getenv("OPENAI_API_KEY")
|
12 |
+
|
13 |
+
st.set_page_config(page_title="Smart Factory RAG Assistant", layout="wide")
|
14 |
+
|
15 |
+
st.title("π Industry 5.0 | Smart Factory RAG Assistant")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
# File Upload
|
18 |
+
uploaded_file = st.file_uploader("π€ Upload your factory CSV data", type=["csv"])
|
19 |
|
20 |
if uploaded_file:
|
21 |
df = pd.read_csv(uploaded_file)
|
22 |
+
st.success("β
File uploaded and loaded!")
|
23 |
+
|
24 |
+
# Basic Preview
|
25 |
+
st.subheader("π Data Preview")
|
26 |
+
st.dataframe(df.head())
|
27 |
+
|
28 |
+
# Descriptive Stats
|
29 |
+
st.subheader("π Descriptive Statistics")
|
30 |
+
st.dataframe(df.describe().T)
|
31 |
+
|
32 |
+
# Correlation Analysis
|
33 |
+
st.subheader("π Parameter Correlation Heatmap")
|
34 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
35 |
+
corr = df.corr(numeric_only=True)
|
36 |
+
sns.heatmap(corr, annot=True, cmap="coolwarm", fmt=".2f", ax=ax)
|
37 |
+
st.pyplot(fig)
|
38 |
|
39 |
# Anomaly Detection
|
40 |
+
st.subheader("β οΈ Anomaly Detection using Isolation Forest")
|
41 |
+
num_df = df.select_dtypes(include='number').dropna()
|
42 |
+
scaler = StandardScaler()
|
43 |
+
X_scaled = scaler.fit_transform(num_df)
|
44 |
+
|
45 |
+
iso = IsolationForest(contamination=0.05)
|
46 |
+
df['Anomaly'] = iso.fit_predict(X_scaled)
|
47 |
+
anomalies = df[df['Anomaly'] == -1]
|
48 |
+
st.write(f"Detected {len(anomalies)} anomalies")
|
49 |
+
st.dataframe(anomalies.head(10))
|
50 |
+
|
51 |
+
# Prepare context for GPT
|
52 |
+
st.subheader("π§ Role-Based Decision Assistant")
|
53 |
+
role = st.selectbox("Select your role", ["Engineer", "Operator"])
|
54 |
+
question = st.text_input("Ask a question based on the data analysis")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
if question:
|
57 |
+
with st.spinner("Thinking..."):
|
58 |
+
summary = df.describe().to_string()
|
59 |
+
corr_text = corr.to_string()
|
60 |
+
anomaly_count = len(anomalies)
|
61 |
+
|
62 |
+
context = f"""
|
63 |
+
You are a highly skilled {role} working in a smart manufacturing facility.
|
64 |
+
|
65 |
+
Here is a summary of the uploaded data:
|
66 |
+
|
67 |
+
STATISTICAL SUMMARY:
|
68 |
+
{summary}
|
69 |
+
|
70 |
+
PARAMETER CORRELATIONS:
|
71 |
+
{corr_text}
|
72 |
+
|
73 |
+
ANOMALY DETECTION:
|
74 |
+
{anomaly_count} anomalies detected using Isolation Forest method.
|
75 |
+
|
76 |
+
Based on this context, answer the following question in a clear, technically accurate manner and suggest best decisions from the point of view of a {role}.
|
77 |
+
"""
|
78 |
+
|
79 |
+
final_prompt = f"""{context}
|
80 |
+
QUESTION: {question}
|
81 |
+
ANSWER:"""
|
82 |
+
|
83 |
+
try:
|
84 |
+
response = openai.ChatCompletion.create(
|
85 |
+
model="gpt-4",
|
86 |
+
messages=[
|
87 |
+
{"role": "system", "content": f"You are an expert {role} in a smart factory."},
|
88 |
+
{"role": "user", "content": final_prompt}
|
89 |
+
],
|
90 |
+
temperature=0.5,
|
91 |
+
max_tokens=500
|
92 |
+
)
|
93 |
+
answer = response['choices'][0]['message']['content']
|
94 |
+
st.success("β
Recommendation:")
|
95 |
+
st.markdown(f"**{answer}**")
|
96 |
+
except Exception as e:
|
97 |
+
st.error(f"β οΈ Error calling GPT API: {str(e)}")
|
98 |
|
99 |
else:
|
100 |
+
st.info("π Please upload a factory CSV data file to begin analysis.")
|