-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecom_dashboard.py
More file actions
528 lines (469 loc) · 23.4 KB
/
secom_dashboard.py
File metadata and controls
528 lines (469 loc) · 23.4 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
"""
SECOM Semiconductor Process Dashboard
=====================================
분석 항목:
1. 수율 예측 (Random Forest + Logistic Regression)
2. 이상탐지 FDC (Hotelling T² 통계량)
3. 변수 중요도 분석 (Feature Importance)
4. SPC 관리도 (Individual + Moving Range)
실행 방법:
pip install streamlit pandas numpy scikit-learn plotly scipy
streamlit run secom_dashboard.py
데이터:
SECOM 데이터셋 (UCI): https://archive.ics.uci.edu/dataset/179/secom
- secom.data (공정 센서 데이터, space-separated)
- secom_labels.data (레이블: -1=정상, 1=불량)
파일이 없으면 자동으로 시뮬레이션 데이터 생성
"""
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix, roc_curve, auc
from sklearn.decomposition import PCA
from sklearn.impute import SimpleImputer
import scipy.stats as stats
import warnings
warnings.filterwarnings("ignore")
# ─────────────────────────────────────────────
# 페이지 설정
# ─────────────────────────────────────────────
st.set_page_config(
page_title="SECOM Process Dashboard",
page_icon="🔬",
layout="wide",
initial_sidebar_state="expanded",
)
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;600&display=swap');
html, body, [class*="css"] { font-family:'IBM Plex Sans',sans-serif; background:#0a0e1a; color:#c8d6e5; }
.stApp { background:#0a0e1a; }
section[data-testid="stSidebar"] { background:#0d1220; border-right:1px solid #1e2d45; }
[data-testid="metric-container"] {
background:linear-gradient(135deg,#0d1220,#111827);
border:1px solid #1e3a5f; border-radius:8px; padding:16px;
}
[data-testid="stMetricValue"] { font-family:'IBM Plex Mono',monospace; font-size:1.8rem!important; color:#38bdf8; }
[data-testid="stMetricDelta"] { font-family:'IBM Plex Mono',monospace; }
[data-testid="stMetricLabel"] { color:#64748b; font-size:0.75rem; letter-spacing:0.1em; text-transform:uppercase; }
h1 { font-family:'IBM Plex Mono',monospace; color:#38bdf8; }
h2,h3 { font-family:'IBM Plex Sans',sans-serif; color:#94a3b8; font-weight:300; letter-spacing:0.05em; }
.stTabs [data-baseweb="tab-list"] { background:#0d1220; border-bottom:1px solid #1e3a5f; gap:4px; }
.stTabs [data-baseweb="tab"] { background:transparent; color:#64748b; font-family:'IBM Plex Mono',monospace; font-size:0.8rem; }
.stTabs [aria-selected="true"] { background:#1e3a5f!important; color:#38bdf8!important; border-radius:4px 4px 0 0; }
hr { border-color:#1e3a5f; }
.stSelectbox>div>div { background:#0d1220; border-color:#1e3a5f; color:#c8d6e5; }
.stAlert { background:#0d1220; border-color:#1e3a5f; }
.banner {
background:linear-gradient(90deg,#0d1220,#0f2035 50%,#0d1220);
border:1px solid #1e3a5f; border-radius:8px; padding:20px 28px; margin-bottom:24px;
}
.banner-title { font-family:'IBM Plex Mono',monospace; font-size:1.5rem; color:#38bdf8; margin:0; }
.banner-sub { font-size:0.8rem; color:#475569; margin-top:4px; letter-spacing:0.08em; }
</style>
""", unsafe_allow_html=True)
# ─────────────────────────────────────────────
# 캐시 전략
# @st.cache_data : load_data() — 파일 I/O, 순수 데이터 반환
# @st.cache_resource : build_pipeline() — 모델 객체 포함, 앱 수명 동안 1회만 실행
# 캐시 없음 : render_*() — 위젯 값을 인자로 받아 매 rerun 즉시 반영
# ─────────────────────────────────────────────
@st.cache_data
def load_data():
"""SECOM 데이터 로드 또는 시뮬레이션 생성"""
try:
X = pd.read_csv("secom.data", sep=" ", header=None)
y_raw = pd.read_csv("secom_labels.data", sep=" ", header=None)
y = (y_raw.iloc[:, 0] == 1).astype(int)
source = "SECOM (실제 데이터)"
except FileNotFoundError:
np.random.seed(42)
n, p = 1567, 591
X = pd.DataFrame(np.random.randn(n, p), columns=[f"F{i+1}" for i in range(p)])
mask = np.random.rand(n, p) < 0.08
X[mask] = np.nan
signal = (X.iloc[:,0]*0.4 + X.iloc[:,5]*(-0.3)
+ X.iloc[:,12]*0.5 + np.random.randn(n)*0.5)
prob = 1 / (1 + np.exp(-signal))
y = pd.Series((prob > 0.82).astype(int))
source = "시뮬레이션 데이터 (secom.data 없음)"
return X, y, source
@st.cache_resource
def build_pipeline():
"""전처리 + 모델 학습 — 앱 기동 시 딱 1회 실행, 객체 재사용"""
X_raw, y, _ = load_data()
# 전처리
imp = SimpleImputer(strategy="mean")
X_imp = pd.DataFrame(imp.fit_transform(X_raw), columns=X_raw.columns)
var_mask = X_imp.var() > 1e-6
X_imp = X_imp.loc[:, var_mask].copy()
scaler = StandardScaler()
X_sc = pd.DataFrame(scaler.fit_transform(X_imp), columns=X_imp.columns)
# 학습/테스트 분리 (numpy 배열로 보관 → 인덱스 충돌 없음)
y_arr = y.values
X_tr, X_te, y_tr, y_te = train_test_split(
X_sc.values, y_arr, test_size=0.2, random_state=42, stratify=y_arr
)
col_names = X_sc.columns.tolist()
# 모델 학습
rf = RandomForestClassifier(n_estimators=200, max_depth=8, random_state=42, n_jobs=-1)
rf.fit(X_tr, y_tr)
lr = LogisticRegression(max_iter=1000, C=0.1, random_state=42)
lr.fit(X_tr, y_tr)
# Hotelling T²
pca = PCA(n_components=10)
scores = pca.fit_transform(X_sc.values)
t2 = np.sum((scores**2) / pca.explained_variance_, axis=1)
n_s, p_t = X_sc.shape
ucl_t2 = ((p_t*(n_s-1)*(n_s+1)) / (n_s*(n_s-p_t))
* stats.f.ppf(0.99, p_t, n_s-p_t))
return {
"X_imp": X_imp,
"col_names": col_names,
"X_tr": X_tr, "X_te": X_te,
"y_tr": y_tr, "y_te": y_te,
"rf": rf, "lr": lr,
"pca": pca, "t2": t2, "ucl": ucl_t2,
}
# ─────────────────────────────────────────────
# 공통 테마
# ─────────────────────────────────────────────
DARK = dict(
paper_bgcolor="#0a0e1a", plot_bgcolor="#0d1220",
font=dict(family="IBM Plex Mono", color="#94a3b8", size=11),
title_font=dict(family="IBM Plex Sans", color="#c8d6e5", size=14),
xaxis=dict(gridcolor="#1e2d45", zerolinecolor="#1e2d45", tickfont=dict(size=10)),
yaxis=dict(gridcolor="#1e2d45", zerolinecolor="#1e2d45", tickfont=dict(size=10)),
margin=dict(l=50, r=30, t=50, b=40),
legend=dict(bgcolor="rgba(0,0,0,0)", bordercolor="#1e3a5f", borderwidth=1),
)
BLUE = "#38bdf8"
ORANGE = "#fb923c"
RED = "#f87171"
GREEN = "#4ade80"
# ─────────────────────────────────────────────
# 탭 렌더링 함수 (캐시 없음 → 위젯 값 즉시 반영)
# ─────────────────────────────────────────────
def render_yield(pipe, y):
st.markdown("### 수율 예측 — Random Forest vs Logistic Regression")
rf, lr = pipe["rf"], pipe["lr"]
X_te, y_te = pipe["X_te"], pipe["y_te"]
y_pred = rf.predict(X_te)
y_prob_rf = rf.predict_proba(X_te)[:, 1]
y_prob_lr = lr.predict_proba(X_te)[:, 1]
fpr_rf, tpr_rf, _ = roc_curve(y_te, y_prob_rf)
fpr_lr, tpr_lr, _ = roc_curve(y_te, y_prob_lr)
auc_rf = auc(fpr_rf, tpr_rf)
auc_lr = auc(fpr_lr, tpr_lr)
col_a, col_b = st.columns(2)
# ROC Curve
fig_roc = go.Figure()
fig_roc.add_trace(go.Scatter(x=fpr_rf, y=tpr_rf,
name=f"Random Forest (AUC={auc_rf:.3f})", line=dict(color=BLUE, width=2.5)))
fig_roc.add_trace(go.Scatter(x=fpr_lr, y=tpr_lr,
name=f"Logistic Reg (AUC={auc_lr:.3f})", line=dict(color=ORANGE, width=2, dash="dash")))
fig_roc.add_trace(go.Scatter(x=[0,1], y=[0,1], name="Random",
line=dict(color="#334155", dash="dot")))
fig_roc.update_layout(**DARK, title="ROC Curve",
xaxis_title="False Positive Rate",
yaxis_title="True Positive Rate", height=380)
col_a.plotly_chart(fig_roc, use_container_width=True)
# Confusion Matrix
cm = confusion_matrix(y_te, y_pred)
fig_cm = go.Figure(go.Heatmap(
z=cm, x=["정상(예측)","불량(예측)"], y=["정상(실제)","불량(실제)"],
colorscale=[[0,"#0d1220"],[0.5,"#1e3a5f"],[1,"#38bdf8"]],
text=cm, texttemplate="%{text}",
textfont=dict(family="IBM Plex Mono", size=22, color="white"),
showscale=False,
))
fig_cm.update_layout(**DARK, title="Confusion Matrix (RF)", height=380)
col_b.plotly_chart(fig_cm, use_container_width=True)
# 예측 확률 분포
df_prob = pd.DataFrame({
"prob": y_prob_rf,
"실제": pd.Series(y_te).map({0:"정상", 1:"불량"}).values,
})
fig_dist = px.histogram(df_prob, x="prob", color="실제", nbins=50, barmode="overlay",
color_discrete_map={"정상":GREEN,"불량":RED}, opacity=0.75)
fig_dist.add_vline(x=0.5, line_dash="dash", line_color=ORANGE,
annotation_text="임계값 0.5", annotation_font_color=ORANGE)
fig_dist.update_layout(**DARK, title="불량 예측 확률 분포",
xaxis_title="P(불량)", yaxis_title="Count", height=300)
st.plotly_chart(fig_dist, use_container_width=True)
# 성능 테이블
rep_rf = classification_report(y_te, y_pred, output_dict=True)
rep_lr = classification_report(y_te, lr.predict(X_te), output_dict=True)
st.markdown("**분류 성능 요약**")
st.dataframe(pd.DataFrame({
"모델": ["Random Forest","Logistic Regression"],
"AUC": [f"{auc_rf:.4f}", f"{auc_lr:.4f}"],
"F1(불량)": [f"{rep_rf.get('1',{}).get('f1-score',0):.4f}",
f"{rep_lr.get('1',{}).get('f1-score',0):.4f}"],
"정밀도": [f"{rep_rf.get('1',{}).get('precision',0):.4f}",
f"{rep_lr.get('1',{}).get('precision',0):.4f}"],
"재현율": [f"{rep_rf.get('1',{}).get('recall',0):.4f}",
f"{rep_lr.get('1',{}).get('recall',0):.4f}"],
}), hide_index=True, use_container_width=True)
def render_fdc(pipe, y, t2_window):
"""t2_window 값이 바뀔 때마다 새로 렌더링"""
st.markdown("### 이상탐지 FDC — Hotelling T² 통계량")
t2, ucl, pca = pipe["t2"], pipe["ucl"], pipe["pca"]
idx = np.arange(t2_window)
t2_w = t2[:t2_window]
y_w = y.values[:t2_window]
fault = t2_w > ucl
fig_t2 = go.Figure()
fig_t2.add_trace(go.Scatter(x=idx[~fault], y=t2_w[~fault], mode="markers",
name="정상", marker=dict(color=BLUE, size=4, opacity=0.7)))
fig_t2.add_trace(go.Scatter(x=idx[fault], y=t2_w[fault], mode="markers",
name="이상 (T²>UCL)", marker=dict(color=RED, size=7, symbol="x", opacity=0.9)))
fig_t2.add_hline(y=ucl, line_dash="dash", line_color=ORANGE, line_width=1.5,
annotation_text=f"UCL = {ucl:.1f}", annotation_font_color=ORANGE,
annotation_position="top right")
for fi in idx[y_w == 1][:50]:
fig_t2.add_vline(x=int(fi), line_color="#ef4444", line_width=0.5, opacity=0.3)
fig_t2.update_layout(**DARK,
title=f"Hotelling T² 모니터링 차트 (샘플 {t2_window}개)",
xaxis_title="Sample Index", yaxis_title="T² 통계량", height=420)
st.plotly_chart(fig_t2, use_container_width=True)
col_c, col_d = st.columns(2)
# PCA 설명력
ev = pca.explained_variance_ratio_ * 100
cv = np.cumsum(ev)
fig_pca = make_subplots(specs=[[{"secondary_y": True}]])
fig_pca.add_trace(go.Bar(x=list(range(1, len(ev)+1)), y=ev,
name="개별 설명력", marker_color=BLUE, opacity=0.8), secondary_y=False)
fig_pca.add_trace(go.Scatter(x=list(range(1, len(cv)+1)), y=cv,
name="누적 설명력", line=dict(color=ORANGE, width=2.5), mode="lines+markers"),
secondary_y=True)
fig_pca.update_layout(**DARK, title="PCA 주성분 설명력", height=320)
fig_pca.update_yaxes(title_text="설명 분산 (%)", secondary_y=False,
gridcolor="#1e2d45", color="#94a3b8")
fig_pca.update_yaxes(title_text="누적 (%)", secondary_y=True,
range=[0, 105], color="#94a3b8")
col_c.plotly_chart(fig_pca, use_container_width=True)
# T² 분포 (정상 vs 불량)
fig_hist = go.Figure()
fig_hist.add_trace(go.Histogram(x=t2[y.values==0], name="정상",
nbinsx=60, marker_color=BLUE, opacity=0.7))
fig_hist.add_trace(go.Histogram(x=t2[y.values==1], name="불량",
nbinsx=60, marker_color=RED, opacity=0.7))
fig_hist.add_vline(x=ucl, line_dash="dash", line_color=ORANGE,
annotation_text="UCL", annotation_font_color=ORANGE)
fig_hist.update_layout(**DARK, title="T² 분포 (정상 vs 불량)",
barmode="overlay", xaxis_title="T²", yaxis_title="Count",
height=320)
col_d.plotly_chart(fig_hist, use_container_width=True)
detect_rate = fault[y_w==1].mean() if y_w.sum() > 0 else 0
st.info(f"**FDC 이상 탐지 결과** | "
f"UCL 초과: **{fault.sum()}개** ({fault.mean()*100:.1f}%) | "
f"실제 불량 탐지율: **{detect_rate*100:.1f}%**")
def render_importance(pipe, y, top_n):
"""top_n이 바뀔 때마다 새로 렌더링"""
st.markdown(f"### 변수 중요도 분석 — Top {top_n}")
rf = pipe["rf"]
X_imp = pipe["X_imp"]
col_names = pipe["col_names"]
importances = pd.Series(rf.feature_importances_, index=col_names)
top_feat = importances.nlargest(top_n).sort_values()
bar_colors = [RED if i >= len(top_feat)-3 else
ORANGE if i >= len(top_feat)-8 else BLUE
for i in range(len(top_feat))]
fig_imp = go.Figure(go.Bar(
x=top_feat.values, y=top_feat.index, orientation="h",
marker_color=bar_colors,
text=[f"{v:.4f}" for v in top_feat.values], textposition="outside",
textfont=dict(family="IBM Plex Mono", size=10, color="#94a3b8"),
))
fig_imp.update_layout(**DARK,
title=f"Top {top_n} Feature Importance (Random Forest)",
xaxis_title="Importance", yaxis_title="",
height=max(350, top_n * 28))
fig_imp.update_yaxes(gridcolor="#1e2d45",
tickfont=dict(family="IBM Plex Mono", size=10))
st.plotly_chart(fig_imp, use_container_width=True)
# Top 3 Box plot
top3 = importances.nlargest(3).index.tolist()
st.markdown(f"**Top 3 변수 분포: `{top3[0]}`, `{top3[1]}`, `{top3[2]}`**")
cols = st.columns(3)
for i, feat in enumerate(top3):
df_box = pd.DataFrame({
"value": X_imp[feat],
"label": y.map({0:"정상", 1:"불량"}),
})
fig_box = px.box(df_box, x="label", y="value", color="label",
color_discrete_map={"정상":BLUE,"불량":RED}, points="all")
fig_box.update_traces(marker_size=2, opacity=0.5)
fig_box.update_layout(**DARK, title=feat, showlegend=False,
height=300, yaxis_title="")
cols[i].plotly_chart(fig_box, use_container_width=True)
# 상세 테이블
st.markdown("**변수 중요도 상세 테이블**")
imp_df = importances.nlargest(top_n).reset_index()
imp_df.columns = ["변수명", "Importance"]
imp_df["누적 기여율 (%)"] = (
imp_df["Importance"].cumsum() / imp_df["Importance"].sum() * 100
).round(2)
imp_df["Importance"] = imp_df["Importance"].round(5)
st.dataframe(imp_df, hide_index=True, use_container_width=True)
def render_spc(pipe, spc_var):
"""spc_var가 바뀔 때마다 새로 렌더링"""
st.markdown(f"### SPC 관리도 — Individual Chart `{spc_var}`")
data = pipe["X_imp"][spc_var].dropna().values
mu = data.mean()
sig = data.std()
ucl = mu + 3*sig; lcl = mu - 3*sig
wu = mu + 2*sig; wl = mu - 2*sig
ooc = (data > ucl) | (data < lcl)
warn = ((data > wu) | (data < wl)) & ~ooc
idx = np.arange(len(data))
fig_spc = go.Figure()
# 구역 배경
fig_spc.add_hrect(y0=wu, y1=ucl, fillcolor=ORANGE, opacity=0.05, line_width=0)
fig_spc.add_hrect(y0=lcl, y1=wl, fillcolor=ORANGE, opacity=0.05, line_width=0)
fig_spc.add_hrect(y0=ucl, y1=float(data.max()*1.5),
fillcolor=RED, opacity=0.05, line_width=0)
fig_spc.add_hrect(y0=float(data.min()*1.5), y1=lcl,
fillcolor=RED, opacity=0.05, line_width=0)
# 관리선
for val, lbl, col, dash in [
(ucl, f"UCL={ucl:.2f}", RED, "dash"),
(lcl, f"LCL={lcl:.2f}", RED, "dash"),
(mu, f"CL ={mu:.2f}", GREEN, "solid"),
(wu, "+2σ", ORANGE, "dot"),
(wl, "−2σ", ORANGE, "dot"),
]:
fig_spc.add_hline(y=val, line_dash=dash, line_color=col, line_width=1.2,
annotation_text=lbl, annotation_font_color=col,
annotation_position="top right")
# 데이터 포인트
fig_spc.add_trace(go.Scatter(
x=idx[~ooc & ~warn], y=data[~ooc & ~warn], mode="lines+markers",
name="정상", line=dict(color=BLUE, width=1), marker=dict(color=BLUE, size=3)))
fig_spc.add_trace(go.Scatter(
x=idx[warn], y=data[warn], mode="markers", name="경고 (2σ)",
marker=dict(color=ORANGE, size=7, symbol="triangle-up")))
fig_spc.add_trace(go.Scatter(
x=idx[ooc], y=data[ooc], mode="markers", name="이상 (OOC)",
marker=dict(color=RED, size=10, symbol="x", line=dict(width=2))))
fig_spc.update_layout(**DARK,
title=f"Individual Control Chart — {spc_var}",
xaxis_title="Sample Index", yaxis_title="Value", height=450)
st.plotly_chart(fig_spc, use_container_width=True)
# 공정 능력 지수
cp = (ucl - lcl) / (6*sig)
cpk = min(ucl - mu, mu - lcl) / (3*sig)
s1,s2,s3,s4,s5 = st.columns(5)
s1.metric("CL", f"{mu:.3f}")
s2.metric("UCL", f"{ucl:.3f}")
s3.metric("LCL", f"{lcl:.3f}")
s4.metric("Cp", f"{cp:.3f}", delta="≥1.33 우수")
s5.metric("Cpk", f"{cpk:.3f}", delta="≥1.33 우수")
# OOC 테이블
if ooc.sum() > 0:
st.markdown(f"**⚠️ OOC 포인트: {ooc.sum()}개 ({ooc.mean()*100:.1f}%)**")
st.dataframe(pd.DataFrame({
"Sample Index": idx[ooc],
"값": data[ooc].round(4),
"UCL": round(ucl, 4),
"LCL": round(lcl, 4),
"상태": ["🔴 이상"] * ooc.sum(),
}).head(20), hide_index=True, use_container_width=True)
else:
st.success("✅ OOC 포인트 없음 — 공정 안정")
# Moving Range
mr = np.abs(np.diff(data))
mr_bar = mr.mean()
ucl_mr = 3.267 * mr_bar
fig_mr = go.Figure()
fig_mr.add_trace(go.Scatter(x=np.arange(len(mr)), y=mr, mode="lines+markers",
name="MR", line=dict(color=BLUE, width=1), marker=dict(size=3)))
fig_mr.add_hline(y=ucl_mr, line_dash="dash", line_color=RED,
annotation_text=f"UCL_MR={ucl_mr:.2f}", annotation_font_color=RED)
fig_mr.add_hline(y=mr_bar, line_color=GREEN, line_dash="solid",
annotation_text=f"MR̄={mr_bar:.2f}", annotation_font_color=GREEN)
fig_mr.update_layout(**DARK, title=f"Moving Range Chart — {spc_var}",
xaxis_title="Sample Index",
yaxis_title="|Xᵢ−Xᵢ₋₁|", height=280)
st.plotly_chart(fig_mr, use_container_width=True)
# ─────────────────────────────────────────────
# 메인
# ─────────────────────────────────────────────
def main():
st.markdown("""
<div class="banner">
<p class="banner-title">🔬 SECOM Process Intelligence Dashboard</p>
<p class="banner-sub">
SEMICONDUCTOR MANUFACTURING · FDC · YIELD PREDICTION · SPC · VARIABLE IMPORTANCE
</p>
</div>
""", unsafe_allow_html=True)
# ── 데이터 & 파이프라인 로드 (캐시)
with st.spinner("모델 초기화 중... (최초 1회)"):
X_raw, y, source = load_data()
pipe = build_pipeline()
t2 = pipe["t2"]
X_imp = pipe["X_imp"]
# ── 사이드바 위젯 (매 rerun마다 읽힘 → render_* 함수에 직접 전달)
with st.sidebar:
st.markdown("### ⚙️ 설정")
st.caption(f"데이터: `{source}`")
st.divider()
top_n = st.slider("변수 중요도 Top N", 5, 30, 15)
t2_window = st.slider("FDC 모니터링 구간", 100, len(t2), 300)
spc_var = st.selectbox("SPC 변수 선택", X_imp.columns[:20].tolist())
st.divider()
st.markdown(f"""
**데이터셋 정보**
- 총 샘플: `{len(y):,}`
- 변수 수: `{X_imp.shape[1]:,}`
- 불량률: `{y.mean()*100:.1f}%`
- 학습/테스트: `{len(pipe["y_tr"]):,}` / `{len(pipe["y_te"]):,}`
""")
# ── KPI 카드
rf = pipe["rf"]
X_te = pipe["X_te"]
y_te = pipe["y_te"]
y_pred = rf.predict(X_te)
y_prob = rf.predict_proba(X_te)[:, 1]
fpr, tpr, _ = roc_curve(y_te, y_prob)
auc_score = auc(fpr, tpr)
f1 = classification_report(y_te, y_pred, output_dict=True).get("1",{}).get("f1-score",0)
t2_faults = (t2 > pipe["ucl"]).sum()
c1,c2,c3,c4,c5 = st.columns(5)
c1.metric("총 웨이퍼", f"{len(y):,}")
c2.metric("불량률", f"{y.mean()*100:.1f}%",
delta=f"{(y.mean()-0.07)*100:+.1f}%p vs 목표 7%", delta_color="inverse")
c3.metric("RF AUC", f"{auc_score:.3f}")
c4.metric("F1 (불량)", f"{f1:.3f}")
c5.metric("FDC 이상 감지", f"{t2_faults:,}",
delta=f"{t2_faults/len(t2)*100:.1f}% 초과")
st.divider()
# ── 탭 (위젯 값을 인자로 넘겨 즉시 반영)
tab1, tab2, tab3, tab4 = st.tabs([
"📈 수율 예측",
"🚨 이상탐지 FDC",
"🔎 변수 중요도",
"📊 SPC 관리도",
])
with tab1: render_yield(pipe, y)
with tab2: render_fdc(pipe, y, t2_window) # t2_window 즉시 반영
with tab3: render_importance(pipe, y, top_n) # top_n 즉시 반영
with tab4: render_spc(pipe, spc_var) # spc_var 즉시 반영
st.divider()
st.markdown(
"<p style='text-align:center;color:#334155;font-size:0.75rem;"
"font-family:IBM Plex Mono'>SECOM Process Intelligence Dashboard · "
"Streamlit + Plotly · 반도체 데이터 분석 포트폴리오</p>",
unsafe_allow_html=True,
)
if __name__ == "__main__":
main()