Spaces:
Sleeping
Sleeping
update dynamic data
Browse files
app.py
CHANGED
|
@@ -52,46 +52,72 @@ ACTION_MAP = {
|
|
| 52 |
log_history = []
|
| 53 |
initial_df_abn = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])
|
| 54 |
|
| 55 |
-
# --- 1. 載入模型與歷史資料 (
|
| 56 |
try:
|
| 57 |
le_action = joblib.load('le_action.pkl')
|
| 58 |
le_ip = joblib.load('le_ip.pkl')
|
| 59 |
|
| 60 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
print("🔄 正在從 Hugging Face 雲端同步最新動態歷史資料...")
|
| 62 |
-
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
if
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
| 69 |
baseline_df['timestamp'] = pd.to_datetime(baseline_df['timestamp'])
|
| 70 |
|
| 71 |
-
#
|
|
|
|
|
|
|
|
|
|
| 72 |
global_stats["total_count"] = len(baseline_df)
|
| 73 |
global_stats["abnormal_count"] = baseline_df[baseline_df['status'].str.contains("異常", na=False)].shape[0]
|
| 74 |
print(f"📊 統計初始化:總監測量 {global_stats['total_count']}, 異常數 {global_stats['abnormal_count']}")
|
| 75 |
|
| 76 |
-
#
|
| 77 |
display_df = baseline_df.sort_values(by='timestamp', ascending=False).head(20).copy()
|
| 78 |
display_df['timestamp'] = display_df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')
|
| 79 |
-
|
|
|
|
| 80 |
|
| 81 |
-
# 異常
|
| 82 |
-
|
| 83 |
-
if
|
| 84 |
-
|
|
|
|
|
|
|
| 85 |
|
|
|
|
| 86 |
baseline_df['month'] = baseline_df['timestamp'].dt.month
|
| 87 |
baseline_df['day'] = baseline_df['timestamp'].dt.day
|
| 88 |
baseline_df['hour'] = baseline_df['timestamp'].dt.hour
|
| 89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
baseline_X = np.column_stack((
|
| 91 |
baseline_df['month'].values,
|
| 92 |
baseline_df['day'].values,
|
| 93 |
baseline_df['hour'].values,
|
| 94 |
-
le_ip.transform(
|
| 95 |
le_action.transform(baseline_df['action'].values)
|
| 96 |
))
|
| 97 |
|
|
@@ -126,7 +152,7 @@ def get_dashboard_html():
|
|
| 126 |
<div class="stat-card card-total">
|
| 127 |
<div class="card-icon">📊</div>
|
| 128 |
<div class="card-content">
|
| 129 |
-
<div class="card-label">總監測量 (
|
| 130 |
<div class="card-value">{total:,} <span class="card-unit">筆 Log</span></div>
|
| 131 |
<div class="card-sub-text">自系統啟動起統計 (+今日即時)</div>
|
| 132 |
</div>
|
|
@@ -154,14 +180,16 @@ def get_dashboard_html():
|
|
| 154 |
"""
|
| 155 |
|
| 156 |
def get_plot_data(selected_key):
|
| 157 |
-
if not selected_key:
|
| 158 |
return None
|
| 159 |
|
| 160 |
action_code = ACTION_MAP.get(selected_key)
|
| 161 |
try:
|
| 162 |
plt.close('all')
|
|
|
|
| 163 |
df_hist = baseline_df[baseline_df['action'] == action_code].copy()
|
| 164 |
|
|
|
|
| 165 |
df_live = pd.DataFrame(log_history)
|
| 166 |
if not df_live.empty:
|
| 167 |
df_live['timestamp'] = pd.to_datetime(df_live['timestamp'])
|
|
@@ -362,9 +390,13 @@ def record_log(ip, cookie, account, role, action, status, time_mode, custom_time
|
|
| 362 |
|
| 363 |
if status == "success" and AI_READY:
|
| 364 |
try:
|
| 365 |
-
pd.DataFrame([new_log]).to_csv('baseline_logs.csv', mode='a', header=False, index=False, encoding='utf-8-sig')
|
| 366 |
current_time = pd.to_datetime(str(log_time))
|
| 367 |
clean_ip = str(ip).split(" ")[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
new_row = np.array([[
|
| 369 |
float(current_time.month), float(current_time.day), float(current_time.hour),
|
| 370 |
float(le_ip.transform([clean_ip])[0]), float(le_action.transform([action])[0])
|
|
@@ -466,7 +498,7 @@ custom_css = """
|
|
| 466 |
|
| 467 |
with gr.Blocks(title="模擬校園入口與資安防護系統") as demo:
|
| 468 |
|
| 469 |
-
# 確保 State 初始化時能抓到剛從雲端下載的最新資料
|
| 470 |
store_df_all = gr.State(value=pd.DataFrame(log_history))
|
| 471 |
store_df_abn = gr.State(value=initial_df_abn)
|
| 472 |
|
|
@@ -475,7 +507,7 @@ with gr.Blocks(title="模擬校園入口與資安防護系統") as demo:
|
|
| 475 |
with gr.Row():
|
| 476 |
with gr.Column(scale=1, elem_classes="mock-panel"):
|
| 477 |
gr.Markdown("### ⚙️ 環境變數模擬器")
|
| 478 |
-
mock_ip = gr.Dropdown(choices=["140.124.71.55 (校內預設)", "140.124.18.22 (宿舍)", "45.33.22.11 (國外異常IP)"], value="140.124.71.55 (校內預設)", allow_custom_value=True, label="模擬來源 IP")
|
| 479 |
mock_cookie = gr.Textbox(label="模擬 Cookie Session ID", value="sess_baseline")
|
| 480 |
gr.Markdown("---")
|
| 481 |
time_mode = gr.Radio(label="時間設定模式", choices=["真實時間 (目前時間)", "自訂時間 (模擬過去/未來)"], value="真實時間 (目前時間)")
|
|
|
|
| 52 |
log_history = []
|
| 53 |
initial_df_abn = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])
|
| 54 |
|
| 55 |
+
# --- 1. 載入模型與歷史資料 (完美整合靜態訓練集與動態資料庫) ---
|
| 56 |
try:
|
| 57 |
le_action = joblib.load('le_action.pkl')
|
| 58 |
le_ip = joblib.load('le_ip.pkl')
|
| 59 |
|
| 60 |
+
# 📁 步驟 A:讀取你的 5 萬筆靜態訓練基底資料
|
| 61 |
+
print("📂 正在讀取靜態訓練基底資料 baseline_logs (1).csv...")
|
| 62 |
+
if os.path.exists('baseline_logs (1).csv'):
|
| 63 |
+
base_df = pd.read_csv('baseline_logs (1).csv')
|
| 64 |
+
else:
|
| 65 |
+
print("⚠️ 找不到 baseline_logs (1).csv,建立空資料表")
|
| 66 |
+
base_df = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])
|
| 67 |
+
|
| 68 |
+
# ☁️ 步驟 B:同步雲端動態歷史資料庫
|
| 69 |
print("🔄 正在從 Hugging Face 雲端同步最新動態歷史資料...")
|
| 70 |
+
dynamic_df = logger_service.sync_from_hf()
|
| 71 |
|
| 72 |
+
# 🤝 步驟 C:將靜態訓練資料與動態資料合併
|
| 73 |
+
if not dynamic_df.empty:
|
| 74 |
+
baseline_df = pd.concat([base_df, dynamic_df], ignore_index=True)
|
| 75 |
+
else:
|
| 76 |
+
baseline_df = base_df.copy()
|
| 77 |
+
|
| 78 |
+
# 確保時間格式正確
|
| 79 |
baseline_df['timestamp'] = pd.to_datetime(baseline_df['timestamp'])
|
| 80 |
|
| 81 |
+
# 🧹 步驟 D:資料清洗 (強制切除 IP 後面的中文字串,保護 AI 模型)
|
| 82 |
+
baseline_df['clean_ip'] = baseline_df['ip_address'].astype(str).apply(lambda x: x.split(" ")[0])
|
| 83 |
+
|
| 84 |
+
# 📊 實現功能 1:統計資料整合 (包含 5萬筆 + 動態新增)
|
| 85 |
global_stats["total_count"] = len(baseline_df)
|
| 86 |
global_stats["abnormal_count"] = baseline_df[baseline_df['status'].str.contains("異常", na=False)].shape[0]
|
| 87 |
print(f"📊 統計初始化:總監測量 {global_stats['total_count']}, 異常數 {global_stats['abnormal_count']}")
|
| 88 |
|
| 89 |
+
# 📜 實現功能 4:即時 Log 顯示最新動態資料
|
| 90 |
display_df = baseline_df.sort_values(by='timestamp', ascending=False).head(20).copy()
|
| 91 |
display_df['timestamp'] = display_df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')
|
| 92 |
+
# 這裡丟給介面的還是原本帶有中文說明的原始 IP 欄位
|
| 93 |
+
log_history = display_df[['timestamp', 'ip_address', 'cookie_id', 'account', 'role', 'action', 'status']].to_dict('records')
|
| 94 |
|
| 95 |
+
# 🚨 實現功能 3:異常 Log 分析區預先載入歷史異常
|
| 96 |
+
abnormal_mask = baseline_df['status'].astype(str).str.contains("異常", na=False)
|
| 97 |
+
if abnormal_mask.any():
|
| 98 |
+
abn_df_temp = baseline_df[abnormal_mask].sort_values(by='timestamp', ascending=False).copy()
|
| 99 |
+
abn_df_temp['timestamp'] = abn_df_temp['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')
|
| 100 |
+
initial_df_abn = abn_df_temp[['timestamp', 'ip_address', 'cookie_id', 'account', 'role', 'action', 'status']]
|
| 101 |
|
| 102 |
+
# --- 準備餵給 AI 建立特徵矩陣 ---
|
| 103 |
baseline_df['month'] = baseline_df['timestamp'].dt.month
|
| 104 |
baseline_df['day'] = baseline_df['timestamp'].dt.day
|
| 105 |
baseline_df['hour'] = baseline_df['timestamp'].dt.hour
|
| 106 |
|
| 107 |
+
# 🧠 核心防護:動態擴增 IP 字典 (解決出現全新 IP 導致崩潰的問題)
|
| 108 |
+
clean_ips = baseline_df['clean_ip'].values
|
| 109 |
+
known_ips = set(le_ip.classes_)
|
| 110 |
+
unknown_ips = set(clean_ips) - known_ips
|
| 111 |
+
if unknown_ips:
|
| 112 |
+
print(f"📖 AI 學習到動態資料庫中的新 IP: {unknown_ips},已自動擴增字典...")
|
| 113 |
+
le_ip.classes_ = np.append(le_ip.classes_, list(unknown_ips))
|
| 114 |
+
|
| 115 |
+
# 建立最終的歷史特徵矩陣
|
| 116 |
baseline_X = np.column_stack((
|
| 117 |
baseline_df['month'].values,
|
| 118 |
baseline_df['day'].values,
|
| 119 |
baseline_df['hour'].values,
|
| 120 |
+
le_ip.transform(clean_ips),
|
| 121 |
le_action.transform(baseline_df['action'].values)
|
| 122 |
))
|
| 123 |
|
|
|
|
| 152 |
<div class="stat-card card-total">
|
| 153 |
<div class="card-icon">📊</div>
|
| 154 |
<div class="card-content">
|
| 155 |
+
<div class="card-label">總監測量 (靜態+動態資料庫)</div>
|
| 156 |
<div class="card-value">{total:,} <span class="card-unit">筆 Log</span></div>
|
| 157 |
<div class="card-sub-text">自系統啟動起統計 (+今日即時)</div>
|
| 158 |
</div>
|
|
|
|
| 180 |
"""
|
| 181 |
|
| 182 |
def get_plot_data(selected_key):
|
| 183 |
+
if not selected_key or not AI_READY:
|
| 184 |
return None
|
| 185 |
|
| 186 |
action_code = ACTION_MAP.get(selected_key)
|
| 187 |
try:
|
| 188 |
plt.close('all')
|
| 189 |
+
# 📊 實現功能 2:圖表整合所有基準資料 (baseline_df 現在已經包含靜態+動態)
|
| 190 |
df_hist = baseline_df[baseline_df['action'] == action_code].copy()
|
| 191 |
|
| 192 |
+
# 加上啟動後即時產生的新資料
|
| 193 |
df_live = pd.DataFrame(log_history)
|
| 194 |
if not df_live.empty:
|
| 195 |
df_live['timestamp'] = pd.to_datetime(df_live['timestamp'])
|
|
|
|
| 390 |
|
| 391 |
if status == "success" and AI_READY:
|
| 392 |
try:
|
|
|
|
| 393 |
current_time = pd.to_datetime(str(log_time))
|
| 394 |
clean_ip = str(ip).split(" ")[0]
|
| 395 |
+
|
| 396 |
+
# 動態補足運行時的新 IP
|
| 397 |
+
if clean_ip not in le_ip.classes_:
|
| 398 |
+
le_ip.classes_ = np.append(le_ip.classes_, clean_ip)
|
| 399 |
+
|
| 400 |
new_row = np.array([[
|
| 401 |
float(current_time.month), float(current_time.day), float(current_time.hour),
|
| 402 |
float(le_ip.transform([clean_ip])[0]), float(le_action.transform([action])[0])
|
|
|
|
| 498 |
|
| 499 |
with gr.Blocks(title="模擬校園入口與資安防護系統") as demo:
|
| 500 |
|
| 501 |
+
# 確保 State 初始化時能抓到剛從雲端下載並合併完的最新資料
|
| 502 |
store_df_all = gr.State(value=pd.DataFrame(log_history))
|
| 503 |
store_df_abn = gr.State(value=initial_df_abn)
|
| 504 |
|
|
|
|
| 507 |
with gr.Row():
|
| 508 |
with gr.Column(scale=1, elem_classes="mock-panel"):
|
| 509 |
gr.Markdown("### ⚙️ 環境變數模擬器")
|
| 510 |
+
mock_ip = gr.Dropdown(choices=["140.124.71.55 (校內預設)", "140.124.18.22 (宿舍)", "114.32.1.45 (未知新IP)", "45.33.22.11 (國外異常IP)"], value="140.124.71.55 (校內預設)", allow_custom_value=True, label="模擬來源 IP")
|
| 511 |
mock_cookie = gr.Textbox(label="模擬 Cookie Session ID", value="sess_baseline")
|
| 512 |
gr.Markdown("---")
|
| 513 |
time_mode = gr.Radio(label="時間設定模式", choices=["真實時間 (目前時間)", "自訂時間 (模擬過去/未來)"], value="真實時間 (目前時間)")
|