PhilipL commited on
Commit
372df3b
·
verified ·
1 Parent(s): b4edf75
Files changed (1) hide show
  1. app.py +595 -269
app.py CHANGED
@@ -1,8 +1,9 @@
1
  import gradio as gr
2
  import datetime
3
  import pandas as pd
 
4
  import joblib
5
- from sklearn.cluster import HDBSCAN
6
  import numpy as np
7
  import logger_service
8
  import os
@@ -11,6 +12,8 @@ import matplotlib.pyplot as plt
11
  import seaborn as sns
12
  import matplotlib.font_manager as fm
13
  import shutil
 
 
14
 
15
  # --- 🌟 解決 Matplotlib 中文顯示問題 ---
16
  font_path = 'SimHei.ttf'
@@ -26,14 +29,33 @@ if os.path.exists(font_path):
26
  plt.rc('font', family='SimHei')
27
  plt.rcParams['axes.unicode_minus'] = False
28
 
29
- # --- 全域統計狀態變數 ---
 
 
 
 
 
 
 
 
30
  global_stats = {
31
  "total_count": 0,
32
  "abnormal_count": 0,
33
  "start_time": datetime.datetime.now()
34
  }
35
 
36
- # --- 13 個系統按鈕的對應字典 ---
 
 
 
 
 
 
 
 
 
 
 
37
  ACTION_MAP = {
38
  "教務系統: 期末網路教學評量": "click_eval_system",
39
  "教務系統: 期末網路預選系統": "click_pre_select_system",
@@ -53,124 +75,169 @@ ACTION_MAP = {
53
  log_history = []
54
  initial_df_abn = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])
55
 
56
- # --- 1. 載入模型與歷史資料 (完美整合靜態訓練集與動態資料庫) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  try:
58
  le_action = joblib.load('le_action.pkl')
59
- le_ip = joblib.load('le_ip.pkl')
60
 
61
- print("📂 正在處理靜態訓練基底資料...")
62
- static_file = 'static_train_data.csv'
63
-
64
- # 🛡️【自動隔離防護盾】避免 5 萬筆資料被 logger_service 覆蓋
65
- if os.path.exists('baseline_logs.csv') and os.path.getsize('baseline_logs.csv') > 500000:
66
- if not os.path.exists(static_file):
67
- shutil.copy('baseline_logs.csv', static_file)
68
- print(f"🛡️ 系統防護:已自動將 5 萬筆訓練資料備份為 '{static_file}' 避免被雲端同步洗掉!")
69
-
70
- # 📁 步驟 A:優先讀取被保護的靜態資料 (或原本的舊檔名)
71
- if os.path.exists(static_file):
72
- base_df = pd.read_csv(static_file)
73
- elif os.path.exists('baseline_logs (1).csv'):
74
- base_df = pd.read_csv('baseline_logs (1).csv')
75
- else:
76
- print("⚠️ 找不到靜態訓練資料,建立空資料表")
77
- base_df = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])
78
-
79
- # ☁️ 步驟 B:同步雲端動態歷史資料庫
80
- print("🔄 正在從 Hugging Face 雲端同步最新動態歷史資料...")
81
- dynamic_df = logger_service.sync_from_hf()
82
-
83
- # 🤝 步驟 C:將靜態訓練資料與動態資料無縫合併
84
- if not dynamic_df.empty:
85
- baseline_df = pd.concat([base_df, dynamic_df], ignore_index=True)
86
- else:
87
- baseline_df = base_df.copy()
88
 
89
- # 確保時間格式正確
90
  baseline_df['timestamp'] = pd.to_datetime(baseline_df['timestamp'])
91
-
92
- # 🧹 步驟 D:資料統一清洗 (強制切除 IP 後面的中文字串,保護 AI 模型)
93
  baseline_df['clean_ip'] = baseline_df['ip_address'].astype(str).apply(lambda x: x.split(" ")[0])
94
 
95
- # 📊 【功能 1】:統計資料整合 (包含 5萬筆 + 動態新增)
96
  global_stats["total_count"] = len(baseline_df)
97
  global_stats["abnormal_count"] = baseline_df[baseline_df['status'].str.contains("異常", na=False)].shape[0]
98
  print(f"📊 統計初始化:總監測量 {global_stats['total_count']}, 異常數 {global_stats['abnormal_count']}")
99
 
100
- # 📜 【功能 4】:即時 Log 顯示最新動態資料
101
  display_df = baseline_df.sort_values(by='timestamp', ascending=False).head(20).copy()
102
  display_df['timestamp'] = display_df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')
103
  log_history = display_df[['timestamp', 'ip_address', 'cookie_id', 'account', 'role', 'action', 'status']].to_dict('records')
104
 
105
- # 🚨 【功能 3】:異常 Log 分析區預先載入歷史異常 (涵蓋動靜態庫)
106
  abnormal_mask = baseline_df['status'].astype(str).str.contains("異常", na=False)
107
  if abnormal_mask.any():
108
  abn_df_temp = baseline_df[abnormal_mask].sort_values(by='timestamp', ascending=False).copy()
109
  abn_df_temp['timestamp'] = abn_df_temp['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')
110
  initial_df_abn = abn_df_temp[['timestamp', 'ip_address', 'cookie_id', 'account', 'role', 'action', 'status']]
111
 
112
- # --- 準備餵給 AI 建立特徵矩陣 ---
113
  baseline_df['month'] = baseline_df['timestamp'].dt.month
114
  baseline_df['day'] = baseline_df['timestamp'].dt.day
115
  baseline_df['hour'] = baseline_df['timestamp'].dt.hour
116
 
117
- # 🧠 核心防護 1:動態擴增 IP 字典
118
- clean_ips = baseline_df['clean_ip'].values
119
- known_ips = set(le_ip.classes_)
120
- unknown_ips = set(clean_ips) - known_ips
121
- if unknown_ips:
122
- print(f"📖 AI 學習到動態資料庫中的新 IP: {unknown_ips},已自動擴增字典...")
123
- le_ip.classes_ = np.append(le_ip.classes_, list(unknown_ips))
124
 
125
- # 🧠 核心防護 2:動態擴增 Action 字典 (解決 login_attempt 等新動作導致崩潰的問題)
126
  actions = baseline_df['action'].astype(str).values
127
  known_actions = set(le_action.classes_)
128
  unknown_actions = set(actions) - known_actions
129
- if unknown_actions:
130
- print(f"📖 AI 學習到動態資料庫中的新動作: {unknown_actions},已自動擴增字典...")
131
- le_action.classes_ = np.append(le_action.classes_, list(unknown_actions))
132
 
133
- # 建立最終的歷史特徵矩陣
134
  baseline_X = np.column_stack((
135
- baseline_df['month'].values,
136
- baseline_df['day'].values,
137
- baseline_df['hour'].values,
138
- le_ip.transform(clean_ips),
139
- le_action.transform(actions)
140
  ))
141
 
142
  AI_READY = True
143
- print("✅ AI 模組與動態歷史基準資料載入成功!")
144
  except Exception as e:
145
  AI_READY = False
146
- global_stats["total_count"] = 0
147
- global_stats["abnormal_count"] = 0
148
  print(f"⚠️ AI 模組載入失敗,請確認檔案。錯誤: {e}")
149
 
150
- USER_DB = {
151
- "student": ["1234", "學生", "同學"],
152
- "admin": ["1234", "管理", "管理員"],
153
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
- # --- 儀表板 HTML ---
156
  def get_dashboard_html():
157
  total = global_stats["total_count"]
158
  abnormal = global_stats["abnormal_count"]
159
  rate = (abnormal / total * 100) if total > 0 else 0
160
 
161
- if not AI_READY:
162
- status_icon, status_text, status_color, status_desc = "🔴", "系統錯誤", "#ef4444", "AI 模型載入失敗,防護停用中。"
163
- elif rate > 10:
164
- status_icon, status_text, status_color, status_desc = "🟡", "高風險警告", "#f59e0b", "近期異常行為頻發,請立刻檢查 Log。"
165
- else:
166
- status_icon, status_text, status_color, status_desc = "🟢", "正常執行", "#10b981", "HDBSCAN 與 Agent 服務運作正常。"
167
 
168
  return f"""
169
  <div class="stat-dashboard">
170
  <div class="stat-card card-total">
171
  <div class="card-icon">📊</div>
172
  <div class="card-content">
173
- <div class="card-label">總監測量 (靜態+動態資料庫)</div>
174
  <div class="card-value">{total:,} <span class="card-unit">筆 Log</span></div>
175
  <div class="card-sub-text">自系統啟動起統計 (+今日即時)</div>
176
  </div>
@@ -197,20 +264,121 @@ def get_dashboard_html():
197
  </div>
198
  """
199
 
200
- def get_plot_data(selected_key):
201
- if not selected_key or not AI_READY:
202
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
 
 
 
 
 
 
 
 
 
 
 
204
  action_code = ACTION_MAP.get(selected_key)
205
  try:
206
  plt.close('all')
207
- # 📊 【功能 2】:圖表整合所有基準資料 (baseline_df 已包含靜態+動態)
208
  df_hist = baseline_df[baseline_df['action'] == action_code].copy()
209
 
210
- # 加上啟動後即時產生的新資料
211
  df_live = pd.DataFrame(log_history)
212
  if not df_live.empty:
213
- df_live['timestamp'] = pd.to_datetime(df_live['timestamp'])
 
214
  df_live = df_live[df_live['action'] == action_code].copy()
215
 
216
  if not df_live.empty:
@@ -242,19 +410,11 @@ def get_plot_data(selected_key):
242
 
243
  if not df_normal.empty:
244
  has_data = True
245
- sns.stripplot(
246
- data=df_normal, x='month', y='time_of_day',
247
- jitter=0.3, alpha=0.4, size=5, color='#10b981',
248
- order=months_order, ax=ax, label='正常資料'
249
- )
250
 
251
  if not df_abnormal.empty:
252
  has_data = True
253
- sns.stripplot(
254
- data=df_abnormal, x='month', y='time_of_day',
255
- jitter=0.3, alpha=0.9, size=9, color='#ef4444', marker='X',
256
- order=months_order, ax=ax, label='異常資料'
257
- )
258
 
259
  if not has_data:
260
  ax.text(0.5, 0.5, f"【{selected_key}】目前尚無資料", ha='center', va='center', fontsize=15)
@@ -267,8 +427,7 @@ def get_plot_data(selected_key):
267
 
268
  handles, labels = ax.get_legend_handles_labels()
269
  by_label = dict(zip(labels, handles))
270
- if by_label:
271
- ax.legend(by_label.values(), by_label.keys(), loc='upper right', bbox_to_anchor=(1.15, 1))
272
 
273
  plt.tight_layout()
274
  return fig
@@ -276,57 +435,83 @@ def get_plot_data(selected_key):
276
  print(f"繪圖失敗: {e}")
277
  return None
278
 
279
- def timer_update(selected_key):
280
- return get_dashboard_html(), get_plot_data(selected_key)
281
 
282
  def explain_abnormal_log(log_text):
283
- if not log_text or log_text.strip() == "":
284
- return "⚠️ 請先提供異常 Log 資訊以進行分析。"
285
- try:
286
- from groq import Groq
287
- except ImportError:
288
- return "⚠️ 未安裝 groq 套件。請在終端機執行 `pip install groq`。"
289
-
290
  groq_api_key = os.environ.get("GROQ_API_KEY", "")
291
- if not groq_api_key:
292
- return "⚠️ 未設定 GROQ_API_KEY。請設定環境變數或直接在程式碼中填寫您的 API Key。"
293
-
294
  try:
295
  client = Groq(api_key=groq_api_key)
296
  response = client.chat.completions.create(
297
  messages=[
298
- {
299
- "role": "system",
300
- "content": "你是一位專業的資安分析師。請根據使用者提供的系統 Log,用繁體中文簡單解釋為什麼這筆 Log 會被標記為異常,並指出可能的資安風險(例如:撞庫攻擊、自動化腳本、半夜作息異常等)。請保持說明在 100 字以內,精簡扼要。"
301
- },
302
- {
303
- "role": "user",
304
- "content": f"請分析這筆異常 Log:\n{log_text}"
305
- }
306
  ],
307
- model="llama-3.1-8b-instant",
308
- temperature=0.5,
309
- max_tokens=300
310
  )
311
  return response.choices[0].message.content
312
- except Exception as e:
313
- return f"⚠️ 呼叫 API 發生錯誤: {str(e)}"
314
 
315
  # --- 2. 核心邏輯與真實 HDBSCAN 異常偵測 ---
316
- def check_anomaly(ip, action, log_time, overall_w, time_w, ip_w, dev_w):
317
  if not AI_READY: return "success"
318
  if action in ["login_attempt", "logout"]: return "success"
319
 
320
  try:
321
- ow, tw, iw, dw = float(overall_w), float(time_w), float(ip_w), float(dev_w)
322
- clean_ip = str(ip).split(" ")[0]
323
- ip_code = float(le_ip.transform([clean_ip])[0])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  action_code = float(le_action.transform([action])[0])
325
 
326
- current_time = pd.to_datetime(str(log_time))
327
- current_month = float(current_time.month)
328
- current_day = float(current_time.day)
329
- current_hour = float(current_time.hour)
330
 
331
  time_multiplier = tw / 100.0
332
  action_scale = (dw / 100.0) * 100.0
@@ -358,17 +543,18 @@ def check_anomaly(ip, action, log_time, overall_w, time_w, ip_w, dev_w):
358
  fit_X = np.vstack((other_history, relevant_history, new_data_point))
359
  strictness = max(2, int(2 + (ow / 100.0) * 4))
360
 
361
- model = HDBSCAN(min_cluster_size=strictness, min_samples=2)
362
  clusters = model.fit_predict(fit_X)
363
 
364
- if clusters[-1] == -1:
365
- return "⚠️異常_作息或行為不符"
366
 
367
  if np.any(same_action_mask):
368
- history_points = scaled_baseline[same_action_mask]
369
- distances = np.linalg.norm(history_points - new_data_point[0], axis=1)
370
  min_distance = np.min(distances)
371
  max_tolerance_distance = time_multiplier * 15.0 + 1.0
 
 
 
372
  if min_distance > max_tolerance_distance:
373
  return "⚠️異常_作息或行為不符"
374
 
@@ -378,118 +564,151 @@ def check_anomaly(ip, action, log_time, overall_w, time_w, ip_w, dev_w):
378
  except Exception as e:
379
  return f"⚠️系統錯誤: {str(e)}"
380
 
381
- def record_log(ip, cookie, account, role, action, status, time_mode, custom_time, ow, tw, iw, dw):
382
  global baseline_X
383
- if time_mode == "自訂時間 (模擬過去/未來)" and custom_time and str(custom_time).strip() != "":
384
- log_time = str(custom_time)
385
- else:
386
- tw_tz = datetime.timezone(datetime.timedelta(hours=8))
387
- log_time = datetime.datetime.now(tw_tz).strftime("%Y-%m-%d %H:%M:%S")
 
 
 
 
 
388
 
389
  if status == "success":
390
- ai_judgment = check_anomaly(ip, action, log_time, ow, tw, iw, dw)
391
  if ai_judgment != "success": status = ai_judgment
392
 
393
- new_log = {
394
- "timestamp": log_time, "ip_address": ip, "cookie_id": cookie,
395
- "account": account, "role": role, "action": action, "status": status
396
- }
397
 
398
- try:
399
- logger_service.push_new_log(new_log)
400
- except:
401
- pass
402
 
403
  global_stats["total_count"] += 1
404
- if "異常" in str(status):
405
- global_stats["abnormal_count"] += 1
406
 
407
  log_history.insert(0, new_log)
408
 
409
  if status == "success" and AI_READY:
410
  try:
411
  current_time = pd.to_datetime(str(log_time))
412
- clean_ip = str(ip).split(" ")[0]
413
-
414
- # 運行時動態擴增未知 IP 與 Action
415
- if clean_ip not in le_ip.classes_:
416
- le_ip.classes_ = np.append(le_ip.classes_, clean_ip)
417
- if action not in le_action.classes_:
418
- le_action.classes_ = np.append(le_action.classes_, action)
419
-
420
- new_row = np.array([[
421
- float(current_time.month), float(current_time.day), float(current_time.hour),
422
- float(le_ip.transform([clean_ip])[0]), float(le_action.transform([action])[0])
423
- ]], dtype=float)
424
  baseline_X = np.vstack((baseline_X, new_row))
425
- except:
426
- pass
427
 
428
  df_all = pd.DataFrame(log_history)
429
- abnormal_logs = [log for log in log_history if "異常" in str(log.get("status", ""))]
430
  df_abnormal = pd.DataFrame(abnormal_logs) if abnormal_logs else pd.DataFrame(columns=df_all.columns)
431
 
432
- if "異常" in str(status):
433
- latest_str = f"時間: {log_time} | IP: {ip} | 帳號: {account} | 動作: {action} | 狀態: {status}"
434
- input_update = gr.update(value=latest_str)
435
- else:
436
- input_update = gr.update()
437
-
438
  return df_all, df_abnormal, input_update
439
 
440
- def fast_login(target_account, ip, cookie, time_mode, custom_time, ow, tw, iw, dw):
441
  role, name = USER_DB[target_account][1], USER_DB[target_account][2]
442
- df_all, df_abn, inp_upd = record_log(ip, cookie, target_account, role, "login_attempt", "success", time_mode, custom_time, ow, tw, iw, dw)
443
- welcome_msg = f"**{name}** 歡迎您 | 線上人數: 938 (⚡快速登入模式)"
444
  target_tab = "student_tab" if role == "學生" else "admin_tab"
445
- return gr.update(selected="dashboard_route"), gr.update(selected=target_tab), "", welcome_msg, df_all, df_abn, inp_upd, target_account
446
-
447
- def process_login(ip, cookie, account, password, captcha, time_mode, custom_time, ow, tw, iw, dw):
448
- valid_captcha = "FEIK"
449
- def fail_response(msg, df_all, df_abn, inp_upd):
450
- return gr.update(selected="login_route"), gr.update(), msg, gr.update(), df_all, df_abn, inp_upd
451
 
 
 
452
  if account not in USER_DB:
453
- df_all, df_abn, inp_upd = record_log(ip, cookie, account, "Unknown", "login_attempt", "failed_no_account", time_mode, custom_time, ow, tw, iw, dw)
454
  return fail_response("帳號不存在!", df_all, df_abn, inp_upd)
455
-
456
  role, name = USER_DB[account][1], USER_DB[account][2]
457
- if captcha.upper() != valid_captcha:
458
- df_all, df_abn, inp_upd = record_log(ip, cookie, account, role, "login_attempt", "failed_captcha", time_mode, custom_time, ow, tw, iw, dw)
459
  return fail_response("驗證碼錯誤!", df_all, df_abn, inp_upd)
460
-
461
  if USER_DB[account][0] == password:
462
- welcome_msg = f"**{name}** 歡迎您 | 線上人數: 938"
463
- df_all, df_abn, inp_upd = record_log(ip, cookie, account, role, "login_attempt", "success", time_mode, custom_time, ow, tw, iw, dw)
464
- target_tab = "student_tab" if role == "學生" else "admin_tab"
465
- return gr.update(selected="dashboard_route"), gr.update(selected=target_tab), "", welcome_msg, df_all, df_abn, inp_upd
466
-
467
- df_all, df_abn, inp_upd = record_log(ip, cookie, account, role, "login_attempt", "failed_password", time_mode, custom_time, ow, tw, iw, dw)
468
  return fail_response("密碼錯誤!", df_all, df_abn, inp_upd)
469
 
470
- def toggle_role(current_account, ip, cookie, time_mode, custom_time, ow, tw, iw, dw):
471
  target_account = "student" if current_account == "admin" else "admin"
472
  role, name = USER_DB[target_account][1], USER_DB[target_account][2]
473
- df_all, df_abn, inp_upd = record_log(ip, cookie, target_account, role, "login_attempt", "success", time_mode, custom_time, ow, tw, iw, dw)
474
- welcome_msg = f"**{name}** 歡迎您 | 線上人數: 938 (⚡單鍵切換模式)"
475
- target_tab = "student_tab" if role == "學生" else "admin_tab"
476
- return gr.update(selected=target_tab), welcome_msg, df_all, df_abn, inp_upd, target_account
477
 
478
- def logout(ip, cookie, account, time_mode, custom_time, ow, tw, iw, dw):
479
  role = USER_DB.get(account, ["", "Unknown"])[1]
480
- df_all, df_abn, inp_upd = record_log(ip, cookie, account, role, "logout", "success", time_mode, custom_time, ow, tw, iw, dw)
481
  return gr.update(selected="login_route"), "", "", "", "", df_all, df_abn, inp_upd
482
 
483
- def simulate_click(ip, cookie, account, button_name, time_mode, custom_time, ow, tw, iw, dw):
484
  role = USER_DB.get(account, ["", "Unknown"])[1]
485
- return record_log(ip, cookie, account, role, button_name, "success", time_mode, custom_time, ow, tw, iw, dw)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
 
487
- def test_anomaly(ip, cookie, account, action_name, test_time_str, ow, tw, iw, dw):
 
 
 
 
 
 
488
  role = USER_DB.get(account, ["", "Unknown"])[1]
489
- return record_log(ip, cookie, account, role, action_name, "success", "自訂時間 (模擬過去/未來)", test_time_str, ow, tw, iw, dw)
490
 
491
- def toggle_time_input(mode):
492
- return gr.update(visible=(mode == "自訂時間 (模擬過去/未來)"))
493
 
494
  # --- 4. UI 介面設計 ---
495
  custom_css = """
@@ -517,17 +736,14 @@ custom_css = """
517
  """
518
 
519
  with gr.Blocks(title="模擬校園��口與資安防護系統") as demo:
520
-
521
- # 確保 State 初始化時能抓到剛從雲端下載並合併完的最新資料
522
  store_df_all = gr.State(value=pd.DataFrame(log_history))
523
  store_df_abn = gr.State(value=initial_df_abn)
524
-
525
  dashboard_timer = gr.Timer(value=60)
526
 
527
  with gr.Row():
528
  with gr.Column(scale=1, elem_classes="mock-panel"):
529
  gr.Markdown("### ⚙️ 環境變數模擬器")
530
- 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")
531
  mock_cookie = gr.Textbox(label="模擬 Cookie Session ID", value="sess_baseline")
532
  gr.Markdown("---")
533
  time_mode = gr.Radio(label="時間設定模式", choices=["真實時間 (目前時間)", "自訂時間 (模擬過去/未來)"], value="真實時間 (目前時間)")
@@ -537,9 +753,7 @@ with gr.Blocks(title="模擬校園入口與資安防護系統") as demo:
537
  log_display = gr.Dataframe(value=pd.DataFrame(log_history), headers=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"], datatype=["str", "str", "str", "str", "str", "str", "str"], interactive=False, wrap=True)
538
 
539
  with gr.Column(scale=2):
540
-
541
  with gr.Tabs(selected="login_route", elem_classes="headless-tabs") as main_router:
542
-
543
  with gr.Tab("Login", id="login_route"):
544
  with gr.Column(elem_classes="login-container"):
545
  gr.Markdown("<div class='ntut-title'>校園入口網站 Taipei Tech Portal</div>")
@@ -562,13 +776,10 @@ with gr.Blocks(title="模擬校園入口與資安防護系統") as demo:
562
  gr.Markdown("### 資訊系統")
563
  welcome_text = gr.Markdown(value="", elem_classes="text-right")
564
  logout_btn = gr.Button("登出", size="sm")
565
-
566
- with gr.Row():
567
- btn_toggle_role = gr.Button("🔄 Student ↔ Admin", size="sm", variant="secondary")
568
  gr.Markdown("---")
569
 
570
  with gr.Tabs(selected="student_tab", elem_classes="headless-tabs") as role_tabs:
571
-
572
  with gr.Tab("👨‍🎓 學生專區", id="student_tab"):
573
  with gr.Accordion("▼ 1. 教務系統", open=True):
574
  with gr.Row(): btn_eval = gr.Button("▶ 期末網路教學評量", size="sm"); btn_pre_select = gr.Button("▶ 期末網路預選系統", size="sm"); btn_add_drop = gr.Button("▶ 開學後加退選系統", size="sm")
@@ -582,40 +793,29 @@ with gr.Blocks(title="模擬校園入口與資安防護系統") as demo:
582
  btn_hack_score = gr.Button("💀 嘗試偷改成績 (SQL Injection)", variant="stop", size="sm")
583
 
584
  with gr.Tab("🛡️ 管理員專區", id="admin_tab"):
585
-
586
  stat_dashboard_display = gr.HTML(value=get_dashboard_html())
587
-
588
  with gr.Accordion("▼ 系統操作時間分佈圖 (即時監控)", open=True, elem_classes="weight-card"):
589
- gr.Markdown("<span style='color:gray; font-size:0.9em;'>選擇下方系統以檢視該系統在歷史與即時紀錄中的時間分佈狀況。圖表每分鐘會自動同步更新,歷史紀錄為綠點,即時攔截之異常為紅叉。</span>")
590
- action_dropdown = gr.Dropdown(
591
- choices=list(ACTION_MAP.keys()),
592
- label="選擇要檢視的系統資料分佈",
593
- value=None
594
- )
595
  action_plot = gr.Plot(show_label=False)
596
 
597
  with gr.Accordion("▼ 防護強度微調 (AI 敏感度)", open=True, elem_classes="weight-card"):
598
- gr.Markdown("<span style='color:gray; font-size:0.9em;'>手動輸入 0~100 的數值。提高強度會增加誤報率,但能更有效攔截新型攻擊。</span>")
599
  with gr.Row():
600
  overall_weight = gr.Number(label="總體防護強度 (%)", value=75, minimum=0, maximum=100)
601
  time_weight = gr.Number(label="時間特徵權重 (%)", value=80, minimum=0, maximum=100)
602
- with gr.Row():
603
  ip_weight = gr.Number(label="IP 聲譽權重 (%)", value=65, minimum=0, maximum=100)
 
604
  device_weight = gr.Number(label="裝置指紋/行為權重 (%)", value=45, minimum=0, maximum=100)
 
 
 
605
 
606
  with gr.Accordion("▼ 異常 Log 分析 (Groq AI Agent)", open=True, elem_classes="weight-card"):
607
- gr.Markdown("<span style='color:gray; font-size:0.9em;'>顯示所有被判定為異常的 Log。點擊分析可讓 AI 代為判讀潛在風險。</span>")
608
- abnormal_log_display = gr.Dataframe(
609
- value=initial_df_abn,
610
- headers=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"],
611
- datatype=["str", "str", "str", "str", "str", "str", "str"],
612
- interactive=False, wrap=True
613
- )
614
  with gr.Row():
615
- abnormal_log_input = gr.Textbox(label="要分析的異常 Log", placeholder="系統若偵測到新異常將會自動填入,您也可以手動修改...", scale=4)
616
  btn_explain_log = gr.Button("🧠 Groq AI 分析", variant="primary", scale=1)
617
-
618
- ai_explanation_output = gr.Textbox(label="AI 分析結果與說明", lines=4, interactive=False, placeholder="等待分析中...")
619
 
620
  with gr.Accordion("▼ HDBSCAN 異常辨識自動化測試區", open=True, elem_classes="weight-card"):
621
  gr.Markdown("<span style='color:gray; font-size:0.9em;'>點擊按鈕將直接以指定時間點執行該系統的操作,結果將顯示於左側 Log 區。</span>")
@@ -646,56 +846,54 @@ with gr.Blocks(title="模擬校園入口與資安防護系統") as demo:
646
  with gr.Row():
647
  t_vdesk_norm = gr.Button("✅ 正常: 軟體雲/WebMail (03-22 18:00)", size="sm"); t_vdesk_anom = gr.Button("⚠️ 異常: 軟體雲/WebMail (08-10 00:00)", size="sm")
648
 
649
- def update_dataframes(df_all, df_abn):
650
- return gr.update(value=df_all), gr.update(value=df_abn)
651
-
652
  store_df_all.change(fn=update_dataframes, inputs=[store_df_all, store_df_abn], outputs=[log_display, abnormal_log_display])
653
 
654
- # --- 綁定事件 ---
655
  demo.load(fn=timer_update, inputs=[action_dropdown], outputs=[stat_dashboard_display, action_plot])
656
  dashboard_timer.tick(fn=timer_update, inputs=[action_dropdown], outputs=[stat_dashboard_display, action_plot])
657
- action_dropdown.change(fn=get_plot_data, inputs=[action_dropdown], outputs=[action_plot])
658
  time_mode.change(fn=toggle_time_input, inputs=time_mode, outputs=custom_time_input)
659
  btn_explain_log.click(fn=explain_abnormal_log, inputs=[abnormal_log_input], outputs=[ai_explanation_output])
660
 
661
- weight_inputs = [overall_weight, time_weight, ip_weight, device_weight]
662
-
 
663
  update_outputs = [main_router, role_tabs, login_msg, welcome_text, store_df_all, store_df_abn, abnormal_log_input]
664
 
665
- login_btn.click(
666
- fn=process_login, inputs=[mock_ip, mock_cookie, acc_input, pwd_input, captcha_input, time_mode, custom_time_input] + weight_inputs, outputs=update_outputs
667
- )
668
 
669
- logout_btn.click(
670
- fn=logout, inputs=[mock_ip, mock_cookie, acc_input, time_mode, custom_time_input] + weight_inputs,
671
- outputs=[main_router, acc_input, pwd_input, captcha_input, login_msg, store_df_all, store_df_abn, abnormal_log_input]
672
- )
673
-
674
- fast_inputs = [mock_ip, mock_cookie, time_mode, custom_time_input] + weight_inputs
675
  fast_outputs = update_outputs + [acc_input]
676
-
677
- btn_fast_student.click(fn=lambda ip, c, tm, ct, ow, tw, iw, dw: fast_login("student", ip, c, tm, ct, ow, tw, iw, dw), inputs=fast_inputs, outputs=fast_outputs)
678
- btn_fast_admin.click(fn=lambda ip, c, tm, ct, ow, tw, iw, dw: fast_login("admin", ip, c, tm, ct, ow, tw, iw, dw), inputs=fast_inputs, outputs=fast_outputs)
679
-
680
- btn_toggle_role.click(
681
- fn=toggle_role, inputs=[acc_input, mock_ip, mock_cookie, time_mode, custom_time_input] + weight_inputs, outputs=[role_tabs, welcome_text, store_df_all, store_df_abn, abnormal_log_input, acc_input]
682
  )
 
 
 
 
 
 
 
683
 
684
  action_mapping = [
685
- (btn_eval, "click_eval_system"), (btn_pre_select, "click_pre_select_system"),
686
- (btn_add_drop, "click_add_drop_system"), (btn_istudy, "click_istudy"),
687
- (btn_card, "click_card_loss"), (btn_course, "click_course_system"),
688
- (btn_score, "click_score_query"), (btn_leave, "click_leave_system"),
689
- (btn_dorm, "click_dorm_system"), (btn_scholarship, "click_scholarship"),
690
- (btn_webmail, "click_webmail"), (btn_vdesk, "click_vdesk"),
691
  (btn_hack_score, "malicious_sql_injection")
692
  ]
693
 
694
  for btn, action_name in action_mapping:
695
  btn.click(
696
- fn=lambda ip, c, acc, t_mode, t_custom, ow, tw, iw, dw, n=action_name: simulate_click(ip, c, acc, n, t_mode, t_custom, ow, tw, iw, dw),
697
- inputs=[mock_ip, mock_cookie, acc_input, time_mode, custom_time_input] + weight_inputs,
698
- outputs=[store_df_all, store_df_abn, abnormal_log_input]
 
699
  )
700
 
701
  test_mapping = [
@@ -703,21 +901,149 @@ with gr.Blocks(title="模擬校園入口與資安防護系統") as demo:
703
  (t_course_norm, "click_course_system", "2026-02-25 07:50:00"), (t_course_anom, "click_course_system", "2026-07-15 05:00:00"),
704
  (t_add_drop_norm, "click_add_drop_system", "2026-02-18 14:00:00"), (t_add_drop_anom, "click_add_drop_system", "2026-05-15 12:00:00"),
705
  (t_eval_norm, "click_eval_system", "2026-12-17 13:20:00"), (t_eval_anom, "click_eval_system", "2026-03-15 03:00:00"),
706
- (t_score_norm, "click_score_query", "2026-11-17 18:50:00"), (t_score_anom, "click_score_query", "2026-02-15 03:00:00"),
707
- (t_dorm_norm, "click_dorm_system", "2026-07-21 23:10:00"), (t_dorm_anom, "click_dorm_system", "2026-11-15 16:00:00"),
708
- (t_schol_norm, "click_scholarship", "2026-03-12 14:00:00"), (t_schol_anom, "click_scholarship", "2026-08-15 02:00:00"),
709
- (t_card_norm, "click_card_loss", "2026-10-23 13:40:00"), (t_card_anom, "click_card_loss", "2026-08-10 03:00:00"),
710
- (t_istudy_norm, "click_istudy", "2026-10-18 16:00:00"), (t_istudy_anom, "click_istudy", "2026-08-20 02:00:00"),
711
- (t_leave_norm, "click_leave_system", "2026-03-29 08:45:00"), (t_leave_anom, "click_leave_system", "2026-08-15 13:00:00"),
712
- (t_vdesk_norm, "click_vdesk", "2026-03-22 18:00:00"), (t_vdesk_anom, "click_vdesk", "2026-08-10 00:00:00")
713
  ]
714
 
715
  for btn, action_name, test_time_str in test_mapping:
716
  btn.click(
717
- fn=lambda ip, c, acc, ow, tw, iw, dw, n=action_name, t_str=test_time_str: test_anomaly(ip, c, acc, n, t_str, ow, tw, iw, dw),
718
- inputs=[mock_ip, mock_cookie, acc_input, overall_weight, time_weight, ip_weight, device_weight],
719
- outputs=[store_df_all, store_df_abn, abnormal_log_input]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720
  )
 
721
 
722
  if __name__ == "__main__":
723
  demo.launch(css=custom_css)
 
1
  import gradio as gr
2
  import datetime
3
  import pandas as pd
4
+ import warnings
5
  import joblib
6
+ import hdbscan
7
  import numpy as np
8
  import logger_service
9
  import os
 
12
  import seaborn as sns
13
  import matplotlib.font_manager as fm
14
  import shutil
15
+ import io
16
+ import base64
17
 
18
  # --- 🌟 解決 Matplotlib 中文顯示問題 ---
19
  font_path = 'SimHei.ttf'
 
29
  plt.rc('font', family='SimHei')
30
  plt.rcParams['axes.unicode_minus'] = False
31
 
32
+ # Seaborn 近期會對舊的 pandas option 發出 FutureWarning(純警告、非功能錯誤)
33
+ # 重整前端會觸發繪圖端點,因此你會在 terminal 看到重複訊息。
34
+ warnings.filterwarnings(
35
+ "ignore",
36
+ category=FutureWarning,
37
+ message="use_inf_as_na option is deprecated*",
38
+ )
39
+
40
+ # --- 全域統計與狀態變數 ---
41
  global_stats = {
42
  "total_count": 0,
43
  "abnormal_count": 0,
44
  "start_time": datetime.datetime.now()
45
  }
46
 
47
+ system_weights = {
48
+ "ow": 75.0, "tw": 80.0, "iw": 65.0,
49
+ "dw": 45.0, "gw": 50.0, "fw": 60.0
50
+ }
51
+
52
+ def update_system_weights(ow, tw, iw, dw, gw, fw):
53
+ system_weights.update({
54
+ "ow": float(ow), "tw": float(tw), "iw": float(iw),
55
+ "dw": float(dw), "gw": float(gw), "fw": float(fw)
56
+ })
57
+ return f"✅ 系統權重已更新 - 總體: {ow}%, 時間: {tw}%, IP: {iw}%, 裝置: {dw}%, 地理: {gw}%, 頻率: {fw}%"
58
+
59
  ACTION_MAP = {
60
  "教務系統: 期末網路教學評量": "click_eval_system",
61
  "教務系統: 期末網路預選系統": "click_pre_select_system",
 
75
  log_history = []
76
  initial_df_abn = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])
77
 
78
+ # HDBSCAN 特徵分群用的 IP 分類
79
+ def get_ip_category(ip_str):
80
+ ip = str(ip_str).split(" ")[0]
81
+ if ip.startswith("140.124."): return 0.0
82
+ elif ip.startswith("61.228."): return 1.0
83
+ elif ip.startswith("210.61."): return 2.0
84
+ elif ip.startswith("45.33."): return 3.0
85
+ else: return 4.0
86
+
87
+ def get_geo_level(ip_str):
88
+ ip = str(ip_str).split(" ")[0]
89
+ if ip == "140.124.71.55": return 0
90
+ elif ip == "140.124.18.22": return 1
91
+ elif ip.startswith("61.228."): return 2
92
+ elif ip.startswith("210.61."): return 3
93
+ elif ip.startswith("45.33."): return 4
94
+ else: return 5
95
+
96
+ # --- 1. 載入模型與歷史資料 ---
97
  try:
98
  le_action = joblib.load('le_action.pkl')
 
99
 
100
+ print("📂 正在讀取本地歷史資料庫...")
101
+ if os.path.exists('baseline_logs.csv'):
102
+ baseline_df = pd.read_csv('baseline_logs.csv')
103
+ else:
104
+ baseline_df = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])
105
+ baseline_df.to_csv('baseline_logs.csv', index=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
 
107
  baseline_df['timestamp'] = pd.to_datetime(baseline_df['timestamp'])
 
 
108
  baseline_df['clean_ip'] = baseline_df['ip_address'].astype(str).apply(lambda x: x.split(" ")[0])
109
 
 
110
  global_stats["total_count"] = len(baseline_df)
111
  global_stats["abnormal_count"] = baseline_df[baseline_df['status'].str.contains("異常", na=False)].shape[0]
112
  print(f"📊 統計初始化:總監測量 {global_stats['total_count']}, 異常數 {global_stats['abnormal_count']}")
113
 
 
114
  display_df = baseline_df.sort_values(by='timestamp', ascending=False).head(20).copy()
115
  display_df['timestamp'] = display_df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')
116
  log_history = display_df[['timestamp', 'ip_address', 'cookie_id', 'account', 'role', 'action', 'status']].to_dict('records')
117
 
 
118
  abnormal_mask = baseline_df['status'].astype(str).str.contains("異常", na=False)
119
  if abnormal_mask.any():
120
  abn_df_temp = baseline_df[abnormal_mask].sort_values(by='timestamp', ascending=False).copy()
121
  abn_df_temp['timestamp'] = abn_df_temp['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')
122
  initial_df_abn = abn_df_temp[['timestamp', 'ip_address', 'cookie_id', 'account', 'role', 'action', 'status']]
123
 
 
124
  baseline_df['month'] = baseline_df['timestamp'].dt.month
125
  baseline_df['day'] = baseline_df['timestamp'].dt.day
126
  baseline_df['hour'] = baseline_df['timestamp'].dt.hour
127
 
128
+ ip_codes = np.array([get_ip_category(ip) for ip in baseline_df['clean_ip'].values])
 
 
 
 
 
 
129
 
 
130
  actions = baseline_df['action'].astype(str).values
131
  known_actions = set(le_action.classes_)
132
  unknown_actions = set(actions) - known_actions
133
+ if unknown_actions: le_action.classes_ = np.append(le_action.classes_, list(unknown_actions))
 
 
134
 
 
135
  baseline_X = np.column_stack((
136
+ baseline_df['month'].values, baseline_df['day'].values, baseline_df['hour'].values,
137
+ ip_codes, le_action.transform(actions)
 
 
 
138
  ))
139
 
140
  AI_READY = True
141
+ print("✅ AI 模組與歷史基準資料載入成功!")
142
  except Exception as e:
143
  AI_READY = False
144
+ global_stats["total_count"] = 0; global_stats["abnormal_count"] = 0
 
145
  print(f"⚠️ AI 模組載入失敗,請確認檔案。錯誤: {e}")
146
 
147
+ USER_DB = {"student": ["1234", "學生", "同學"], "admin": ["1234", "管理", "管理員"]}
148
+
149
+
150
+ # =====================================================================
151
+ # 👉 新增:純淨 API 端點專用函式 (只回傳 JSON 字典,給隊友抓資料用)
152
+ # =====================================================================
153
+ def api_get_stats():
154
+ """取得系統狀態與權重"""
155
+ total = global_stats["total_count"]
156
+ abnormal = global_stats["abnormal_count"]
157
+ rate = round((abnormal / total * 100), 2) if total > 0 else 0
158
+ return {
159
+ "status": "success",
160
+ "ai_ready": AI_READY,
161
+ "data": {
162
+ "total_logs": total,
163
+ "abnormal_logs": abnormal,
164
+ "anomaly_rate_percent": rate,
165
+ "current_weights": system_weights
166
+ }
167
+ }
168
+
169
+ def api_get_logs(limit=20):
170
+ """取得最新的 N 筆 Log"""
171
+ try: limit = int(limit)
172
+ except: limit = 20
173
+ return {
174
+ "status": "success",
175
+ "count": len(log_history[:limit]),
176
+ "data": log_history[:limit]
177
+ }
178
+
179
+ def api_get_chart_data(action_name):
180
+ """取得特定系統的圖表原始數據 (供前端自行繪圖)"""
181
+ if not AI_READY: return {"status": "error", "message": "AI 模型未載入"}
182
+ action_code = ACTION_MAP.get(action_name)
183
+ if not action_code: return {"status": "error", "message": f"找不到系統: {action_name}"}
184
+
185
+ df_hist = baseline_df[baseline_df['action'] == action_code].copy()
186
+ df_live = pd.DataFrame(log_history)
187
+ if not df_live.empty:
188
+ df_live['timestamp'] = pd.to_datetime(df_live['timestamp'], errors='coerce')
189
+ df_live = df_live.dropna(subset=['timestamp'])
190
+ df_live = df_live[df_live['action'] == action_code].copy()
191
+
192
+ if not df_live.empty:
193
+ df_combined = pd.concat([df_hist, df_live], ignore_index=True)
194
+ df_combined = df_combined.drop_duplicates(subset=['timestamp', 'account', 'action'])
195
+ else:
196
+ df_combined = df_hist.copy()
197
+
198
+ if df_combined.empty:
199
+ return {"status": "success", "action": action_code, "data": {"normal": [], "abnormal": []}}
200
+
201
+ df_combined['month'] = df_combined['timestamp'].dt.month
202
+ df_combined['time_of_day'] = df_combined['timestamp'].dt.hour + df_combined['timestamp'].dt.minute / 60.0
203
+
204
+ is_abnormal = df_combined['status'].astype(str).str.contains("異常", na=False)
205
+
206
+ normal_data = df_combined[~is_abnormal][['month', 'time_of_day', 'timestamp']].astype(str).to_dict('records')
207
+ abnormal_data = df_combined[is_abnormal][['month', 'time_of_day', 'timestamp', 'status']].astype(str).to_dict('records')
208
+
209
+ return {
210
+ "status": "success",
211
+ "action_code": action_code,
212
+ "data": {"normal": normal_data, "abnormal": abnormal_data}
213
+ }
214
+
215
+ def api_get_abnormal_logs():
216
+ """取得所有異常 Log"""
217
+ abnormal_logs = [log for log in log_history if "異常" in str(log.get("status", "")) or "錯誤" in str(log.get("status", "")) or "受限" in str(log.get("status", ""))]
218
+ return {
219
+ "status": "success",
220
+ "count": len(abnormal_logs),
221
+ "data": abnormal_logs
222
+ }
223
+ # =====================================================================
224
+
225
 
 
226
  def get_dashboard_html():
227
  total = global_stats["total_count"]
228
  abnormal = global_stats["abnormal_count"]
229
  rate = (abnormal / total * 100) if total > 0 else 0
230
 
231
+ if not AI_READY: status_icon, status_text, status_color, status_desc = "🔴", "系統錯誤", "#ef4444", "AI 模型載入失敗,防護停用中。"
232
+ elif rate > 10: status_icon, status_text, status_color, status_desc = "🟡", "高風險警告", "#f59e0b", "近期異常行為頻發,請立刻檢查 Log。"
233
+ else: status_icon, status_text, status_color, status_desc = "🟢", "正常執行", "#10b981", "HDBSCAN 與 Agent 服務運作正常。"
 
 
 
234
 
235
  return f"""
236
  <div class="stat-dashboard">
237
  <div class="stat-card card-total">
238
  <div class="card-icon">📊</div>
239
  <div class="card-content">
240
+ <div class="card-label">總監測量 (本地歷史資料庫)</div>
241
  <div class="card-value">{total:,} <span class="card-unit">筆 Log</span></div>
242
  <div class="card-sub-text">自系統啟動起統計 (+今日即時)</div>
243
  </div>
 
264
  </div>
265
  """
266
 
267
+ def get_plot_data_for_api(selected_key):
268
+ """API專用版本,返回Base64圖片字符串"""
269
+ if not selected_key or not AI_READY: return None
270
+ action_code = ACTION_MAP.get(selected_key)
271
+ try:
272
+ plt.close('all')
273
+ df_hist = baseline_df[baseline_df['action'] == action_code].copy()
274
+
275
+ df_live = pd.DataFrame(log_history)
276
+ if not df_live.empty:
277
+ df_live['timestamp'] = pd.to_datetime(df_live['timestamp'], errors='coerce')
278
+ df_live = df_live.dropna(subset=['timestamp'])
279
+ df_live = df_live[df_live['action'] == action_code].copy()
280
+
281
+ if not df_live.empty:
282
+ df_combined = pd.concat([df_hist, df_live], ignore_index=True)
283
+ df_combined = df_combined.drop_duplicates(subset=['timestamp', 'account', 'action'])
284
+ else:
285
+ df_combined = df_hist.copy()
286
+
287
+ if df_combined.empty:
288
+ fig, ax = plt.subplots(figsize=(12, 6))
289
+ if os.path.exists(font_path): plt.rc('font', family='SimHei')
290
+ ax.text(0.5, 0.5, f"【{selected_key}】目前尚無資料", ha='center', va='center', fontsize=15)
291
+ # 將圖片轉換為 Base64
292
+ buf = io.BytesIO()
293
+ fig.savefig(buf, format='png', dpi=100, bbox_inches='tight')
294
+ buf.seek(0)
295
+ img_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
296
+ buf.close()
297
+ plt.close(fig)
298
+ return f"data:image/png;base64,{img_base64}"
299
+
300
+ df_combined['month'] = df_combined['timestamp'].dt.month
301
+ df_combined['time_of_day'] = df_combined['timestamp'].dt.hour + df_combined['timestamp'].dt.minute / 60.0
302
+
303
+ is_abnormal = df_combined['status'].astype(str).str.contains("異常", na=False)
304
+ df_normal = df_combined[~is_abnormal]
305
+ df_abnormal = df_combined[is_abnormal]
306
+
307
+ fig, ax = plt.subplots(figsize=(12, 6))
308
+ sns.set_theme(style="whitegrid")
309
+ if os.path.exists(font_path): plt.rc('font', family='SimHei')
310
+ plt.rcParams['axes.unicode_minus'] = False
311
+
312
+ has_data = False
313
+ months_order = list(range(1, 13))
314
+
315
+ if not df_normal.empty:
316
+ has_data = True
317
+ sns.stripplot(data=df_normal, x='month', y='time_of_day', jitter=0.3, alpha=0.4, size=5, color='#10b981', order=months_order, ax=ax, label='正常資料')
318
+
319
+ if not df_abnormal.empty:
320
+ has_data = True
321
+ sns.stripplot(data=df_abnormal, x='month', y='time_of_day', jitter=0.3, alpha=0.9, size=9, color='#ef4444', marker='X', order=months_order, ax=ax, label='異常資料')
322
+
323
+ if not has_data:
324
+ ax.text(0.5, 0.5, f"【{selected_key}】目前尚無資料", ha='center', va='center', fontsize=15)
325
+ # 將圖片轉換為 Base64
326
+ buf = io.BytesIO()
327
+ fig.savefig(buf, format='png', dpi=100, bbox_inches='tight')
328
+ buf.seek(0)
329
+ img_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
330
+ buf.close()
331
+ plt.close(fig)
332
+ return f"data:image/png;base64,{img_base64}"
333
+
334
+ ax.set_xlabel('月份 (1 ~ 12月)', fontsize=12)
335
+ ax.set_ylabel('時間 (24小時制)', fontsize=12)
336
+ ax.set_yticks(np.arange(0, 25, 2))
337
+ ax.set_ylim(24.5, -0.5)
338
+
339
+ handles, labels = ax.get_legend_handles_labels()
340
+ by_label = dict(zip(labels, handles))
341
+ if by_label: ax.legend(by_label.values(), by_label.keys(), loc='upper right', bbox_to_anchor=(1.15, 1))
342
+
343
+ plt.tight_layout()
344
+
345
+ # 將圖片轉換為 Base64
346
+ buf = io.BytesIO()
347
+ fig.savefig(buf, format='png', dpi=100, bbox_inches='tight')
348
+ buf.seek(0)
349
+ img_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
350
+ buf.close()
351
+ plt.close(fig)
352
+ return f"data:image/png;base64,{img_base64}"
353
+ except Exception as e:
354
+ print(f"繪圖失敗: {e}")
355
+ # 返回一個簡單的錯誤圖片
356
+ fig, ax = plt.subplots(figsize=(8, 4))
357
+ ax.text(0.5, 0.5, f"圖表生成失敗: {str(e)}", ha='center', va='center', fontsize=12, color='red')
358
+ ax.set_xlim(0, 1)
359
+ ax.set_ylim(0, 1)
360
+ ax.axis('off')
361
 
362
+ buf = io.BytesIO()
363
+ fig.savefig(buf, format='png', dpi=100, bbox_inches='tight')
364
+ buf.seek(0)
365
+ img_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')
366
+ buf.close()
367
+ plt.close(fig)
368
+ return f"data:image/png;base64,{img_base64}"
369
+
370
+ def get_plot_data(selected_key):
371
+ """給Gradio界面使用,返回Figure對象"""
372
+ if not selected_key or not AI_READY: return None
373
  action_code = ACTION_MAP.get(selected_key)
374
  try:
375
  plt.close('all')
 
376
  df_hist = baseline_df[baseline_df['action'] == action_code].copy()
377
 
 
378
  df_live = pd.DataFrame(log_history)
379
  if not df_live.empty:
380
+ df_live['timestamp'] = pd.to_datetime(df_live['timestamp'], errors='coerce')
381
+ df_live = df_live.dropna(subset=['timestamp'])
382
  df_live = df_live[df_live['action'] == action_code].copy()
383
 
384
  if not df_live.empty:
 
410
 
411
  if not df_normal.empty:
412
  has_data = True
413
+ sns.stripplot(data=df_normal, x='month', y='time_of_day', jitter=0.3, alpha=0.4, size=5, color='#10b981', order=months_order, ax=ax, label='正常資料')
 
 
 
 
414
 
415
  if not df_abnormal.empty:
416
  has_data = True
417
+ sns.stripplot(data=df_abnormal, x='month', y='time_of_day', jitter=0.3, alpha=0.9, size=9, color='#ef4444', marker='X', order=months_order, ax=ax, label='異常資料')
 
 
 
 
418
 
419
  if not has_data:
420
  ax.text(0.5, 0.5, f"【{selected_key}】目前尚無資料", ha='center', va='center', fontsize=15)
 
427
 
428
  handles, labels = ax.get_legend_handles_labels()
429
  by_label = dict(zip(labels, handles))
430
+ if by_label: ax.legend(by_label.values(), by_label.keys(), loc='upper right', bbox_to_anchor=(1.15, 1))
 
431
 
432
  plt.tight_layout()
433
  return fig
 
435
  print(f"繪圖失敗: {e}")
436
  return None
437
 
438
+ def timer_update(selected_key): return get_dashboard_html(), get_plot_data(selected_key)
 
439
 
440
  def explain_abnormal_log(log_text):
441
+ if not log_text or log_text.strip() == "": return "⚠️ 請先提供異常 Log 資訊以進行分析。"
442
+ try: from groq import Groq
443
+ except ImportError: return "⚠️ 未安裝 groq 套件。請在終端機執行 `pip install groq`。"
 
 
 
 
444
  groq_api_key = os.environ.get("GROQ_API_KEY", "")
445
+ if not groq_api_key: return "⚠️ 未設定 GROQ_API_KEY。"
 
 
446
  try:
447
  client = Groq(api_key=groq_api_key)
448
  response = client.chat.completions.create(
449
  messages=[
450
+ {"role": "system", "content": "你是一位專業的資安分析師。請簡單解釋為什麼這筆 Log 異常,並指出風險(如撞庫攻擊、作息異常等)。"},
451
+ {"role": "user", "content": f"請分析這筆異常 Log:\n{log_text}"}
 
 
 
 
 
 
452
  ],
453
+ model="llama-3.1-8b-instant", temperature=0.5, max_tokens=300
 
 
454
  )
455
  return response.choices[0].message.content
456
+ except Exception as e: return f"⚠️ 呼叫 API 發生錯誤: {str(e)}"
 
457
 
458
  # --- 2. 核心邏輯與真實 HDBSCAN 異常偵測 ---
459
+ def check_anomaly(ip, account, action, log_time):
460
  if not AI_READY: return "success"
461
  if action in ["login_attempt", "logout"]: return "success"
462
 
463
  try:
464
+ ow = float(system_weights["ow"])
465
+ tw = float(system_weights["tw"])
466
+ iw = float(system_weights["iw"])
467
+ dw = float(system_weights["dw"])
468
+ gw = float(system_weights["gw"])
469
+ fw = float(system_weights["fw"])
470
+
471
+ geo_level = get_geo_level(ip)
472
+
473
+ if gw == 100 and geo_level > 0:
474
+ return "⚠️異常_地理位置受限 (100%絕對鎖定: 僅限校內專網存取)"
475
+ elif gw >= 90 and geo_level > 1:
476
+ return "⚠️異常_地理位置受限 (高敏感防護: 僅限校園網路與宿舍)"
477
+ elif gw >= 70 and geo_level > 2:
478
+ return "⚠️異常_地理位置受限 (進階防護: 禁止公共場所與海外連線)"
479
+ elif gw >= 50 and geo_level > 3:
480
+ return "⚠️異常_地理位置受限 (預設防護: 禁止海外異常 IP)"
481
+
482
+ current_dt = pd.to_datetime(str(log_time))
483
+ cutoff_dt = current_dt - pd.Timedelta(seconds=60)
484
+
485
+ recent_clicks = 0
486
+ for log in log_history:
487
+ log_dt = pd.to_datetime(log['timestamp'])
488
+ if log_dt >= cutoff_dt:
489
+ if log.get('account') == account and log.get('action') == action:
490
+ recent_clicks += 1
491
+ else:
492
+ break
493
+
494
+ if fw <= 0: max_allowed_clicks = 100
495
+ elif fw <= 10: max_allowed_clicks = 90
496
+ elif fw <= 20: max_allowed_clicks = 80
497
+ elif fw <= 30: max_allowed_clicks = 70
498
+ elif fw <= 40: max_allowed_clicks = 60
499
+ elif fw <= 50: max_allowed_clicks = 50
500
+ elif fw <= 60: max_allowed_clicks = 40
501
+ elif fw <= 70: max_allowed_clicks = 30
502
+ elif fw <= 80: max_allowed_clicks = 15
503
+ elif fw <= 90: max_allowed_clicks = 9
504
+ else: max_allowed_clicks = 3
505
+
506
+ if (recent_clicks + 1) > max_allowed_clicks:
507
+ return f"⚠️異常_單一操作頻率過高 ({recent_clicks+1}次/分)"
508
+
509
+ ip_code = float(get_ip_category(ip))
510
  action_code = float(le_action.transform([action])[0])
511
 
512
+ current_month = float(current_dt.month)
513
+ current_day = float(current_dt.day)
514
+ current_hour = float(current_dt.hour)
 
515
 
516
  time_multiplier = tw / 100.0
517
  action_scale = (dw / 100.0) * 100.0
 
543
  fit_X = np.vstack((other_history, relevant_history, new_data_point))
544
  strictness = max(2, int(2 + (ow / 100.0) * 4))
545
 
546
+ model = hdbscan.HDBSCAN(min_cluster_size=strictness, min_samples=2)
547
  clusters = model.fit_predict(fit_X)
548
 
549
+ if clusters[-1] == -1: return "⚠️異常_作息或行為不符"
 
550
 
551
  if np.any(same_action_mask):
552
+ distances = np.linalg.norm(relevant_history - new_data_point[0], axis=1)
 
553
  min_distance = np.min(distances)
554
  max_tolerance_distance = time_multiplier * 15.0 + 1.0
555
+
556
+ if ip_code >= 3.0: max_tolerance_distance *= (1 - (iw / 100.0) * 0.6)
557
+
558
  if min_distance > max_tolerance_distance:
559
  return "⚠️異常_作息或行為不符"
560
 
 
564
  except Exception as e:
565
  return f"⚠️系統錯誤: {str(e)}"
566
 
567
+ def record_log(ip, cookie, account, role, action, status, time_mode, custom_time):
568
  global baseline_X
569
+
570
+ if time_mode == "自訂時間 (模擬過去/未來)" and custom_time and str(custom_time).strip() != "":
571
+ try:
572
+ valid_time = pd.to_datetime(str(custom_time))
573
+ log_time = valid_time.strftime("%Y-%m-%d %H:%M:%S")
574
+ except Exception:
575
+ log_time = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S")
576
+ status = "⚠️格式錯誤_無效的自訂時間"
577
+ else:
578
+ log_time = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))).strftime("%Y-%m-%d %H:%M:%S")
579
 
580
  if status == "success":
581
+ ai_judgment = check_anomaly(ip, account, action, log_time)
582
  if ai_judgment != "success": status = ai_judgment
583
 
584
+ new_log = {"timestamp": log_time, "ip_address": ip, "cookie_id": cookie, "account": account, "role": role, "action": action, "status": status}
585
+
586
+ new_df = pd.DataFrame([new_log])
587
+ new_df.to_csv('baseline_logs.csv', mode='a', header=not os.path.exists('baseline_logs.csv'), index=False)
588
 
589
+ try: logger_service.push_new_log(new_log)
590
+ except: pass
 
 
591
 
592
  global_stats["total_count"] += 1
593
+ if "異常" in str(status) or "錯誤" in str(status) or "受限" in str(status): global_stats["abnormal_count"] += 1
 
594
 
595
  log_history.insert(0, new_log)
596
 
597
  if status == "success" and AI_READY:
598
  try:
599
  current_time = pd.to_datetime(str(log_time))
600
+ if action not in le_action.classes_: le_action.classes_ = np.append(le_action.classes_, action)
601
+ new_row = np.array([[float(current_time.month), float(current_time.day), float(current_time.hour), float(get_ip_category(ip)), float(le_action.transform([action])[0])]], dtype=float)
 
 
 
 
 
 
 
 
 
 
602
  baseline_X = np.vstack((baseline_X, new_row))
603
+ except: pass
 
604
 
605
  df_all = pd.DataFrame(log_history)
606
+ abnormal_logs = [log for log in log_history if "異常" in str(log.get("status", "")) or "錯誤" in str(log.get("status", "")) or "受限" in str(log.get("status", ""))]
607
  df_abnormal = pd.DataFrame(abnormal_logs) if abnormal_logs else pd.DataFrame(columns=df_all.columns)
608
 
609
+ input_update = gr.update(value=f"時間: {log_time} | IP: {ip} | 帳號: {account} | 動作: {action} | 狀態: {status}") if "異常" in str(status) or "錯誤" in str(status) or "受限" in str(status) else gr.update()
 
 
 
 
 
610
  return df_all, df_abnormal, input_update
611
 
612
+ def fast_login(target_account, ip, cookie, time_mode, custom_time):
613
  role, name = USER_DB[target_account][1], USER_DB[target_account][2]
614
+ df_all, df_abn, inp_upd = record_log(ip, cookie, target_account, role, "login_attempt", "success", time_mode, custom_time)
 
615
  target_tab = "student_tab" if role == "學生" else "admin_tab"
616
+ return gr.update(selected="dashboard_route"), gr.update(selected=target_tab), "", f"**{name}** 歡迎您 | 線上人數: 938 (⚡快速登入模式)", df_all, df_abn, inp_upd, target_account
 
 
 
 
 
617
 
618
+ def process_login(ip, cookie, account, password, captcha, time_mode, custom_time):
619
+ def fail_response(msg, df_all, df_abn, inp_upd): return gr.update(selected="login_route"), gr.update(), msg, gr.update(), df_all, df_abn, inp_upd
620
  if account not in USER_DB:
621
+ df_all, df_abn, inp_upd = record_log(ip, cookie, account, "Unknown", "login_attempt", "failed_no_account", time_mode, custom_time)
622
  return fail_response("帳號不存在!", df_all, df_abn, inp_upd)
 
623
  role, name = USER_DB[account][1], USER_DB[account][2]
624
+ if captcha.upper() != "FEIK":
625
+ df_all, df_abn, inp_upd = record_log(ip, cookie, account, role, "login_attempt", "failed_captcha", time_mode, custom_time)
626
  return fail_response("驗證碼錯誤!", df_all, df_abn, inp_upd)
 
627
  if USER_DB[account][0] == password:
628
+ df_all, df_abn, inp_upd = record_log(ip, cookie, account, role, "login_attempt", "success", time_mode, custom_time)
629
+ return gr.update(selected="dashboard_route"), gr.update(selected="student_tab" if role == "學生" else "admin_tab"), "", f"**{name}** 歡迎您 | 線上人數: 938", df_all, df_abn, inp_upd
630
+ df_all, df_abn, inp_upd = record_log(ip, cookie, account, role, "login_attempt", "failed_password", time_mode, custom_time)
 
 
 
631
  return fail_response("密碼錯誤!", df_all, df_abn, inp_upd)
632
 
633
+ def toggle_role(current_account, ip, cookie, time_mode, custom_time):
634
  target_account = "student" if current_account == "admin" else "admin"
635
  role, name = USER_DB[target_account][1], USER_DB[target_account][2]
636
+ df_all, df_abn, inp_upd = record_log(ip, cookie, target_account, role, "login_attempt", "success", time_mode, custom_time)
637
+ return gr.update(selected="student_tab" if role == "學生" else "admin_tab"), f"**{name}** 歡迎您 | 線上人數: 938 (⚡單鍵切換模式)", df_all, df_abn, inp_upd, target_account
 
 
638
 
639
+ def logout(ip, cookie, account, time_mode, custom_time):
640
  role = USER_DB.get(account, ["", "Unknown"])[1]
641
+ df_all, df_abn, inp_upd = record_log(ip, cookie, account, role, "logout", "success", time_mode, custom_time)
642
  return gr.update(selected="login_route"), "", "", "", "", df_all, df_abn, inp_upd
643
 
644
+ def simulate_click(ip, cookie, account, button_name, time_mode, custom_time):
645
  role = USER_DB.get(account, ["", "Unknown"])[1]
646
+ return record_log(ip, cookie, account, role, button_name, "success", time_mode, custom_time)
647
+
648
+ def _extract_gr_update_value(update_obj):
649
+ """
650
+ Gradio 的 gr.update(...) 可能回傳 dict 形式或物件形式。
651
+ 這裡統一抓出其中的 `value`,否則回傳 None。
652
+ """
653
+ if update_obj is None:
654
+ return None
655
+ if isinstance(update_obj, dict):
656
+ return update_obj.get("value")
657
+ # Fallback: try attribute access
658
+ try:
659
+ return getattr(update_obj, "value", None)
660
+ except Exception:
661
+ return None
662
+
663
+ def api_run_student_action(ip, c, acc, button_name, tm, ct):
664
+ """
665
+ 統一的 student action API handler:
666
+ - 呼叫 simulate_click 真正寫入 log
667
+ - 只回傳異常/受限/錯誤時 abnormal_log_input 的字串(正常時回傳空字串)
668
+ """
669
+ df_all, df_abn, inp_upd = simulate_click(ip, c, acc, button_name, tm, ct)
670
+ val = _extract_gr_update_value(inp_upd)
671
+ return val or ""
672
+
673
+ def api_run_student_action_code(ip, c, acc, action_code, tm, ct):
674
+ """
675
+ Generic student action API.
676
+ Vue 會直接傳 action_code(例如 click_eval_system / malicious_sql_injection)
677
+ """
678
+ df_all, df_abn, inp_upd = simulate_click(ip, c, acc, action_code, tm, ct)
679
+ val = _extract_gr_update_value(inp_upd)
680
+ # 回傳 store 的新資料(讓前端 update_dataframes 能讀到),以及異常字串給 Vue 顯示
681
+ return df_all, df_abn, val or ""
682
+
683
+ def api_lambda(ip, c, tm, ct):
684
+ # Vue: lambda(期末教學評量) 沒有傳 acc => 預設用學生帳號
685
+ default_acc = USER_DB["student"][0]
686
+ return api_run_student_action(ip, c, default_acc, "click_eval_system", tm, ct)
687
+
688
+ def api_lambda_1(ip, c, tm, ct):
689
+ default_acc = USER_DB["student"][0]
690
+ return api_run_student_action(ip, c, default_acc, "click_pre_select_system", tm, ct)
691
+
692
+ def api_lambda_7(ip, c, acc, tm, ct):
693
+ return api_run_student_action(ip, c, acc, "click_leave_system", tm, ct)
694
+
695
+ def api_lambda_8(ip, c, acc, tm, ct):
696
+ return api_run_student_action(ip, c, acc, "click_dorm_system", tm, ct)
697
+
698
+ def api_lambda_10(ip, c, acc, tm, ct):
699
+ return api_run_student_action(ip, c, acc, "click_webmail", tm, ct)
700
 
701
+ def api_lambda_11(ip, c, acc, tm, ct):
702
+ return api_run_student_action(ip, c, acc, "click_vdesk", tm, ct)
703
+
704
+ def api_lambda_12(ip, c, acc, tm, ct):
705
+ return api_run_student_action(ip, c, acc, "malicious_sql_injection", tm, ct)
706
+
707
+ def test_anomaly(ip, cookie, account, action_name, test_time_str):
708
  role = USER_DB.get(account, ["", "Unknown"])[1]
709
+ return record_log(ip, cookie, account, role, action_name, "success", "自訂時間 (模擬過去/未來)", test_time_str)
710
 
711
+ def toggle_time_input(mode): return gr.update(visible=(mode == "自訂時間 (模擬過去/未來)"))
 
712
 
713
  # --- 4. UI 介面設計 ---
714
  custom_css = """
 
736
  """
737
 
738
  with gr.Blocks(title="模擬校園��口與資安防護系統") as demo:
 
 
739
  store_df_all = gr.State(value=pd.DataFrame(log_history))
740
  store_df_abn = gr.State(value=initial_df_abn)
 
741
  dashboard_timer = gr.Timer(value=60)
742
 
743
  with gr.Row():
744
  with gr.Column(scale=1, elem_classes="mock-panel"):
745
  gr.Markdown("### ⚙️ 環境變數模擬器")
746
+ mock_ip = gr.Dropdown(choices=["140.124.71.55 (校內預設)", "140.124.18.22 (宿舍)", "61.228.45.112 (家裡)", "210.61.47.88 (公共場所)", "45.33.22.11 (國外異常IP)"], value="140.124.71.55 (校內預設)", allow_custom_value=True, label="模擬來源 IP")
747
  mock_cookie = gr.Textbox(label="模擬 Cookie Session ID", value="sess_baseline")
748
  gr.Markdown("---")
749
  time_mode = gr.Radio(label="時間設定模式", choices=["真實時間 (目前時間)", "自訂時間 (模擬過去/未來)"], value="真實時間 (目前時間)")
 
753
  log_display = gr.Dataframe(value=pd.DataFrame(log_history), headers=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"], datatype=["str", "str", "str", "str", "str", "str", "str"], interactive=False, wrap=True)
754
 
755
  with gr.Column(scale=2):
 
756
  with gr.Tabs(selected="login_route", elem_classes="headless-tabs") as main_router:
 
757
  with gr.Tab("Login", id="login_route"):
758
  with gr.Column(elem_classes="login-container"):
759
  gr.Markdown("<div class='ntut-title'>校園入口網站 Taipei Tech Portal</div>")
 
776
  gr.Markdown("### 資訊系統")
777
  welcome_text = gr.Markdown(value="", elem_classes="text-right")
778
  logout_btn = gr.Button("登出", size="sm")
779
+ with gr.Row(): btn_toggle_role = gr.Button("🔄 Student ↔ Admin", size="sm", variant="secondary")
 
 
780
  gr.Markdown("---")
781
 
782
  with gr.Tabs(selected="student_tab", elem_classes="headless-tabs") as role_tabs:
 
783
  with gr.Tab("👨‍🎓 學生專區", id="student_tab"):
784
  with gr.Accordion("▼ 1. 教務系統", open=True):
785
  with gr.Row(): btn_eval = gr.Button("▶ 期末網路教學評量", size="sm"); btn_pre_select = gr.Button("▶ 期末網路預選系統", size="sm"); btn_add_drop = gr.Button("▶ 開學後加退選系統", size="sm")
 
793
  btn_hack_score = gr.Button("💀 嘗試偷改成績 (SQL Injection)", variant="stop", size="sm")
794
 
795
  with gr.Tab("🛡️ 管理員專區", id="admin_tab"):
 
796
  stat_dashboard_display = gr.HTML(value=get_dashboard_html())
 
797
  with gr.Accordion("▼ 系統操作時間分佈圖 (即時監控)", open=True, elem_classes="weight-card"):
798
+ action_dropdown = gr.Dropdown(choices=list(ACTION_MAP.keys()), label="選擇要檢視的系統資料分佈", value=None)
 
 
 
 
 
799
  action_plot = gr.Plot(show_label=False)
800
 
801
  with gr.Accordion("▼ 防護強度微調 (AI 敏感度)", open=True, elem_classes="weight-card"):
802
+ gr.Markdown("<span style='color:gray; font-size:0.9em;'>動態防護已全面啟動:包含 HDBSCAN 空間異常偵測、IP 聲譽聯防,以及動態視窗頻率攔截。</span>")
803
  with gr.Row():
804
  overall_weight = gr.Number(label="總體防護強度 (%)", value=75, minimum=0, maximum=100)
805
  time_weight = gr.Number(label="時間特徵權重 (%)", value=80, minimum=0, maximum=100)
 
806
  ip_weight = gr.Number(label="IP 聲譽權重 (%)", value=65, minimum=0, maximum=100)
807
+ with gr.Row():
808
  device_weight = gr.Number(label="裝置指紋/行為權重 (%)", value=45, minimum=0, maximum=100)
809
+ geo_weight = gr.Number(label="🌍 地理偏移敏感度 (%)", value=50, minimum=0, maximum=100)
810
+ freq_weight = gr.Number(label="⚡ 行為頻率敏感度 (%)", value=60, minimum=0, maximum=100)
811
+ weights_status = gr.Textbox(value="", visible=False)
812
 
813
  with gr.Accordion("▼ 異常 Log 分析 (Groq AI Agent)", open=True, elem_classes="weight-card"):
814
+ abnormal_log_display = gr.Dataframe(value=initial_df_abn, headers=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"], datatype=["str", "str", "str", "str", "str", "str", "str"], interactive=False, wrap=True)
 
 
 
 
 
 
815
  with gr.Row():
816
+ abnormal_log_input = gr.Textbox(label="要分析的異常 Log", placeholder="系統若偵測到新異常將會自動填入...", scale=4)
817
  btn_explain_log = gr.Button("🧠 Groq AI 分析", variant="primary", scale=1)
818
+ ai_explanation_output = gr.Textbox(label="AI 分析結果與說明", lines=4, interactive=False)
 
819
 
820
  with gr.Accordion("▼ HDBSCAN 異常辨識自動化測試區", open=True, elem_classes="weight-card"):
821
  gr.Markdown("<span style='color:gray; font-size:0.9em;'>點擊按鈕將直接以指定時間點執行該系統的操作,結果將顯示於左側 Log 區。</span>")
 
846
  with gr.Row():
847
  t_vdesk_norm = gr.Button("✅ 正常: 軟體雲/WebMail (03-22 18:00)", size="sm"); t_vdesk_anom = gr.Button("⚠️ 異常: 軟體雲/WebMail (08-10 00:00)", size="sm")
848
 
849
+ def update_dataframes(df_all, df_abn): return gr.update(value=df_all), gr.update(value=df_abn)
 
 
850
  store_df_all.change(fn=update_dataframes, inputs=[store_df_all, store_df_abn], outputs=[log_display, abnormal_log_display])
851
 
 
852
  demo.load(fn=timer_update, inputs=[action_dropdown], outputs=[stat_dashboard_display, action_plot])
853
  dashboard_timer.tick(fn=timer_update, inputs=[action_dropdown], outputs=[stat_dashboard_display, action_plot])
854
+ action_dropdown.change(fn=get_plot_data, inputs=[action_dropdown], outputs=[action_plot], api_name="getPlotData")
855
  time_mode.change(fn=toggle_time_input, inputs=time_mode, outputs=custom_time_input)
856
  btn_explain_log.click(fn=explain_abnormal_log, inputs=[abnormal_log_input], outputs=[ai_explanation_output])
857
 
858
+ # weight_inputs = [overall_weight, time_weight, ip_weight, device_weight, geo_weight, freq_weight]
859
+ # 移除所有 UI 欄位的 update_system_weights 綁定,僅保留 API 專用端點
860
+
861
  update_outputs = [main_router, role_tabs, login_msg, welcome_text, store_df_all, store_df_abn, abnormal_log_input]
862
 
863
+ login_btn.click(fn=process_login, inputs=[mock_ip, mock_cookie, acc_input, pwd_input, captcha_input, time_mode, custom_time_input], outputs=update_outputs)
864
+ logout_btn.click(fn=logout, inputs=[mock_ip, mock_cookie, acc_input, time_mode, custom_time_input], outputs=[main_router, acc_input, pwd_input, captcha_input, login_msg, store_df_all, store_df_abn, abnormal_log_input])
 
865
 
866
+ fast_inputs = [mock_ip, mock_cookie, time_mode, custom_time_input]
 
 
 
 
 
867
  fast_outputs = update_outputs + [acc_input]
868
+
869
+ btn_fast_student.click(
870
+ fn=lambda ip, c, tm, ct: fast_login("student", ip, c, tm, ct),
871
+ inputs=fast_inputs,
872
+ outputs=fast_outputs,
873
+ api_name=None
874
  )
875
+ btn_fast_admin.click(
876
+ fn=lambda ip, c, tm, ct: fast_login("admin", ip, c, tm, ct),
877
+ inputs=fast_inputs,
878
+ outputs=fast_outputs,
879
+ api_name=None
880
+ )
881
+ btn_toggle_role.click(fn=toggle_role, inputs=[acc_input, mock_ip, mock_cookie, time_mode, custom_time_input], outputs=[role_tabs, welcome_text, store_df_all, store_df_abn, abnormal_log_input, acc_input])
882
 
883
  action_mapping = [
884
+ (btn_eval, "click_eval_system"), (btn_pre_select, "click_pre_select_system"), (btn_add_drop, "click_add_drop_system"),
885
+ (btn_istudy, "click_istudy"), (btn_card, "click_card_loss"), (btn_course, "click_course_system"),
886
+ (btn_score, "click_score_query"), (btn_leave, "click_leave_system"), (btn_dorm, "click_dorm_system"),
887
+ (btn_scholarship, "click_scholarship"), (btn_webmail, "click_webmail"), (btn_vdesk, "click_vdesk"),
 
 
888
  (btn_hack_score, "malicious_sql_injection")
889
  ]
890
 
891
  for btn, action_name in action_mapping:
892
  btn.click(
893
+ fn=lambda ip, c, acc, tm, ct, n=action_name: simulate_click(ip, c, acc, n, tm, ct),
894
+ inputs=[mock_ip, mock_cookie, acc_input, time_mode, custom_time_input],
895
+ outputs=[store_df_all, store_df_abn, abnormal_log_input],
896
+ api_name=None
897
  )
898
 
899
  test_mapping = [
 
901
  (t_course_norm, "click_course_system", "2026-02-25 07:50:00"), (t_course_anom, "click_course_system", "2026-07-15 05:00:00"),
902
  (t_add_drop_norm, "click_add_drop_system", "2026-02-18 14:00:00"), (t_add_drop_anom, "click_add_drop_system", "2026-05-15 12:00:00"),
903
  (t_eval_norm, "click_eval_system", "2026-12-17 13:20:00"), (t_eval_anom, "click_eval_system", "2026-03-15 03:00:00"),
904
+ (t_score_norm, "click_score_query", "2026-11-17 18:50:00"), (t_score_anom, "click_score_query", "2026-02-15 03:00:00")
 
 
 
 
 
 
905
  ]
906
 
907
  for btn, action_name, test_time_str in test_mapping:
908
  btn.click(
909
+ fn=lambda ip, c, acc, n=action_name, t_str=test_time_str: test_anomaly(ip, c, acc, n, t_str),
910
+ inputs=[mock_ip, mock_cookie, acc_input],
911
+ outputs=[store_df_all, store_df_abn, abnormal_log_input],
912
+ api_name=None
913
+ )
914
+
915
+ # =====================================================================
916
+ # 👉 新增:隱藏的 UI 綁定區 (讓外部能透過 api_name 存取資料)
917
+ # =====================================================================
918
+ with gr.Group(visible=False):
919
+ api_stats_btn = gr.Button("API_Stats")
920
+ api_stats_out = gr.JSON()
921
+ api_stats_btn.click(fn=api_get_stats, inputs=[], outputs=[api_stats_out], api_name="get_stats")
922
+
923
+ api_logs_btn = gr.Button("API_Logs")
924
+ api_logs_in = gr.Number(value=20)
925
+ api_logs_out = gr.JSON()
926
+ api_logs_btn.click(fn=api_get_logs, inputs=[api_logs_in], outputs=[api_logs_out], api_name="get_logs")
927
+
928
+ api_chart_btn = gr.Button("API_Chart")
929
+ api_chart_in = gr.Textbox()
930
+ api_chart_out = gr.JSON()
931
+ api_chart_btn.click(fn=api_get_chart_data, inputs=[api_chart_in], outputs=[api_chart_out], api_name="get_chart_data")
932
+
933
+ api_abnormal_logs_btn = gr.Button("API_Abnormal_Logs")
934
+ api_abnormal_logs_out = gr.JSON()
935
+ api_abnormal_logs_btn.click(fn=api_get_abnormal_logs, inputs=[], outputs=[api_abnormal_logs_out], api_name="get_abnormal_logs")
936
+
937
+ api_plot_btn = gr.Button("API_Plot")
938
+ api_plot_in = gr.Textbox()
939
+ api_plot_out = gr.Textbox()
940
+ api_plot_btn.click(fn=get_plot_data_for_api, inputs=[api_plot_in], outputs=[api_plot_out], api_name="get_plot_data_api")
941
+
942
+ # System weights update API endpoint
943
+ api_update_weights_btn = gr.Button("API_Update_Weights")
944
+ api_update_weights_ow = gr.Number(label="Overall Weight")
945
+ api_update_weights_tw = gr.Number(label="Time Weight")
946
+ api_update_weights_iw = gr.Number(label="IP Weight")
947
+ api_update_weights_dw = gr.Number(label="Device Weight")
948
+ api_update_weights_gw = gr.Number(label="Geo Weight")
949
+ api_update_weights_fw = gr.Number(label="Frequency Weight")
950
+ api_update_weights_in = [api_update_weights_ow, api_update_weights_tw, api_update_weights_iw, api_update_weights_dw, api_update_weights_gw, api_update_weights_fw]
951
+ api_update_weights_out = gr.Textbox()
952
+ api_update_weights_btn.click(fn=update_system_weights, inputs=api_update_weights_in, outputs=[api_update_weights_out], api_name="update_system_weights")
953
+
954
+ # ================================================================
955
+ # Vue student actions API endpoints
956
+ # - 對應 Digital-Bodyguard-Fontend/src/App.vue 裡的 ACTION_ENDPOINTS
957
+ # - 對應 Digital-Bodyguard-Fontend/src/services/gradioService.ts 的 lambda*
958
+ # ================================================================
959
+ api_student_ip = gr.Textbox(label="ip")
960
+ api_student_cookie = gr.Textbox(label="c")
961
+ api_student_time_mode = gr.Radio(label="tm", choices=["真實時間 (目前時間)", "自訂時間 (模擬過去/未來)"], value="真實時間 (目前時間)")
962
+ api_student_custom_time = gr.Textbox(label="ct")
963
+
964
+ # lambda (期末教學評量) => api_name="lambda"
965
+ api_lambda_out = gr.Textbox()
966
+ gr.Button("API_lambda", visible=False).click(
967
+ fn=api_lambda,
968
+ inputs=[api_student_ip, api_student_cookie, api_student_time_mode, api_student_custom_time],
969
+ outputs=[api_lambda_out],
970
+ api_name="lambda",
971
+ )
972
+
973
+ # lambda_1 (預選系統)
974
+ api_lambda_1_out = gr.Textbox()
975
+ gr.Button("API_lambda_1", visible=False).click(
976
+ fn=api_lambda_1,
977
+ inputs=[api_student_ip, api_student_cookie, api_student_time_mode, api_student_custom_time],
978
+ outputs=[api_lambda_1_out],
979
+ api_name="lambda_1",
980
+ )
981
+
982
+ # lambda_7 (請假系統)
983
+ api_lambda_acc = gr.Textbox(label="acc")
984
+ api_lambda_7_out = gr.Textbox()
985
+ gr.Button("API_lambda_7", visible=False).click(
986
+ fn=api_lambda_7,
987
+ inputs=[api_student_ip, api_student_cookie, api_lambda_acc, api_student_time_mode, api_student_custom_time],
988
+ outputs=[api_lambda_7_out],
989
+ api_name="lambda_7",
990
+ )
991
+
992
+ # lambda_8 (宿舍登錄)
993
+ api_lambda_8_out = gr.Textbox()
994
+ gr.Button("API_lambda_8", visible=False).click(
995
+ fn=api_lambda_8,
996
+ inputs=[api_student_ip, api_student_cookie, api_lambda_acc, api_student_time_mode, api_student_custom_time],
997
+ outputs=[api_lambda_8_out],
998
+ api_name="lambda_8",
999
+ )
1000
+
1001
+ # lambda_10 (網路郵局)
1002
+ api_lambda_10_out = gr.Textbox()
1003
+ gr.Button("API_lambda_10", visible=False).click(
1004
+ fn=api_lambda_10,
1005
+ inputs=[api_student_ip, api_student_cookie, api_lambda_acc, api_student_time_mode, api_student_custom_time],
1006
+ outputs=[api_lambda_10_out],
1007
+ api_name="lambda_10",
1008
+ )
1009
+
1010
+ # lambda_11 (軟體雲)
1011
+ api_lambda_11_out = gr.Textbox()
1012
+ gr.Button("API_lambda_11", visible=False).click(
1013
+ fn=api_lambda_11,
1014
+ inputs=[api_student_ip, api_student_cookie, api_lambda_acc, api_student_time_mode, api_student_custom_time],
1015
+ outputs=[api_lambda_11_out],
1016
+ api_name="lambda_11",
1017
+ )
1018
+
1019
+ # lambda_12 (SQL Injection)
1020
+ api_lambda_12_out = gr.Textbox()
1021
+ gr.Button("API_lambda_12", visible=False).click(
1022
+ fn=api_lambda_12,
1023
+ inputs=[api_student_ip, api_student_cookie, api_lambda_acc, api_student_time_mode, api_student_custom_time],
1024
+ outputs=[api_lambda_12_out],
1025
+ api_name="lambda_12",
1026
+ )
1027
+
1028
+ # ================================================================
1029
+ # Generic student action API (Vue 一次呼叫任意系統按鈕)
1030
+ # ================================================================
1031
+ api_student_action_code = gr.Textbox(label="action_code")
1032
+ api_student_run_out = gr.Textbox()
1033
+ gr.Button("API_RunStudentAction", visible=False).click(
1034
+ fn=api_run_student_action_code,
1035
+ inputs=[
1036
+ api_student_ip,
1037
+ api_student_cookie,
1038
+ api_lambda_acc,
1039
+ api_student_action_code,
1040
+ api_student_time_mode,
1041
+ api_student_custom_time,
1042
+ ],
1043
+ outputs=[store_df_all, store_df_abn, api_student_run_out],
1044
+ api_name="run_student_action",
1045
  )
1046
+ # =====================================================================
1047
 
1048
  if __name__ == "__main__":
1049
  demo.launch(css=custom_css)