-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
161 lines (138 loc) Β· 7.1 KB
/
app.py
File metadata and controls
161 lines (138 loc) Β· 7.1 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
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
from data_loader import get_logs, get_log_by_id
st.set_page_config(page_title="Intrusion Detection Admin", page_icon="π¨", layout="wide")
st.markdown("""
<style>
.metric-card {
background-color: #f8f9fa;
padding: 15px;
border-radius: 8px;
border-left: 5px solid #ccc;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
margin-bottom: 10px;
}
.metric-label { font-size: 0.85rem; color: #666; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
.metric-value { font-size: 1.1rem; font-weight: bold; color: #333; margin-top: 5px; }
.metric-delta { font-size: 0.9rem; margin-top: 3px; }
</style>
""", unsafe_allow_html=True)
st.title("π¨ Network Anomaly Inspector")
st.markdown("XAI κΈ°λ° λ€νΈμν¬ μΉ¨μ
νμ§ μμ€ν
κ΄λ¦¬μ λμ보λ")
# --- 1. μ¬μ΄λλ°: λ‘κ·Έ μ ν ---
st.sidebar.header("Log Selection")
# λ°μ΄ν° λ‘λ
df_summary, raw_logs = get_logs()
if df_summary.empty:
st.error("νμν λ‘κ·Έ λ°μ΄ν°κ° μμ΅λλ€. JSON νμΌ κ²½λ‘λ₯Ό νμΈν΄μ£ΌμΈμ.")
st.info("μμ κ²½λ‘: /ExplainableBug/kafka/autoencoder/xai_results/*.json")
else:
selected_log_id = st.sidebar.selectbox(
"Select Suspicious Packet:",
df_summary['ID'].tolist(),
format_func=lambda x: f"{x} (Loss: {df_summary[df_summary['ID']==x]['Total Loss'].values[0]})"
)
if selected_log_id:
log_data = get_log_by_id(selected_log_id)
if log_data:
# --- μλ¨: ν΅μ¬ μμ½ μ 보 ---
col1, col2, col3 = st.columns(3)
with col1:
threshold = log_data.get('threshold', 100)
loss = log_data.get('total_loss', 0)
st.metric(
"Anomaly Score (Loss)",
f"{loss:.2f}",
delta=f"Threshold: {threshold}",
delta_color="inverse"
)
with col2:
st.metric("Timestamp", log_data.get('timestamp', 'N/A'))
with col3:
filename = log_data.get('raw_data', {}).get('filename', 'Unknown')
st.metric("Source File", filename)
st.divider()
# --- λ©μΈ λΆμ μμ (2λ¨ λΆλ¦¬) ---
col_shap, col_raw = st.columns([1, 1])
# ---------------------------------------------------------
# [Left Column] SHAP Analysis (Top 3 Focus)
# ---------------------------------------------------------
with col_shap:
st.subheader("π Why Malicious? (Top 3 Factors)")
st.caption("AIκ° μ΄ ν¨ν·μ λΉμ μμΌλ‘ νλ¨νκ² λ§λ κ°μ₯ ν° μμΈ 3κ°μ§μ
λλ€.")
shap_data = log_data.get('shap_values', {})
if shap_data:
# μ«μν κ°λ§ νν°λ§ ν μ λκ° κΈ°μ€μΌλ‘ μ λ ¬νμ¬ Top 3 μΆμΆ
valid_shap = {k: v for k, v in shap_data.items() if isinstance(v, (int, float))}
sorted_shap = sorted(valid_shap.items(), key=lambda x: abs(x[1]), reverse=True)
top_3 = sorted_shap[:3]
if top_3:
# Top 3 μΉ΄λ ννλ‘ κ°μ‘° νμ
for idx, (feature, value) in enumerate(top_3):
# μμ(μ
μ± κΈ°μ¬)λ λΉ¨κ°μ, μμ(μ μ κΈ°μ¬)λ νλμ
impact_color = "#ef4444" if value > 0 else "#3b82f6"
impact_text = "Risk Increase β¬" if value > 0 else "Risk Decrease β¬"
st.markdown(f"""
<div class="metric-card" style="border-left-color: {impact_color};">
<div class="metric-label">Top {idx+1} Contributor</div>
<div class="metric-value">{feature}</div>
<div class="metric-delta" style="color:{impact_color};">
Value: {value:.4f} ({impact_text})
</div>
</div>
""", unsafe_allow_html=True)
# μ 체 λ§₯λ½μ μν μ°¨νΈ (Top 10)
with st.expander("View Detailed Chart (Top 10)", expanded=True):
top_10 = sorted_shap[:10]
features = [x[0] for x in top_10]
values = [x[1] for x in top_10]
colors = ['#ef4444' if v > 0 else '#3b82f6' for v in values]
fig = go.Figure(go.Bar(
x=values, y=features, orientation='h', marker_color=colors
))
fig.update_layout(
margin=dict(l=0, r=0, t=0, b=0),
height=350,
yaxis=dict(autorange="reversed"),
xaxis_title="SHAP Value"
)
# use_container_width=Trueλ μ μ§ (Plotly μ°¨νΈμλ μ ν¨ν¨)
st.plotly_chart(fig, use_container_width=True)
else:
st.info("No numeric SHAP values found.")
else:
st.warning("No SHAP values available.")
# ---------------------------------------------------------
# [Right Column] Raw Data (Fully Dynamic)
# ---------------------------------------------------------
with col_raw:
st.subheader("π Packet Details (Dynamic)")
st.caption("ν¨ν·μ μλ³Έ λ°μ΄ν°λ₯Ό ν
μ΄λΈ ννλ‘ νμν©λλ€. (νλ μλ κ°μ§)")
raw_data = log_data.get('raw_data', {})
if raw_data:
df_raw = pd.DataFrame(
list(raw_data.items()),
columns=["Field Name", "Value"]
)
# λͺ¨λ κ°μ λ¬Έμμ΄λ‘ λ³ννμ¬ νμ μ€λ₯ λ°©μ§
df_raw['Value'] = df_raw['Value'].astype(str)
# ν
μ΄λΈ νμ
st.dataframe(
df_raw,
width="stretch",
hide_index=True,
height=600,
column_config={
"Field Name": st.column_config.TextColumn("Field Name", width="medium"),
"Value": st.column_config.TextColumn("Captured Value", width="large")
}
)
else:
st.warning("No raw data captured.")
st.divider()
# νλ¨: Kafka λ©νλ°μ΄ν°
with st.expander("Broker Information (Kafka)", expanded=False):
st.json(log_data.get('kafka_info', {}))
else:
st.error("λ‘κ·Έ λ°μ΄ν°λ₯Ό λΆλ¬μ€λ μ€ μ€λ₯κ° λ°μνμ΅λλ€.")