Delete app.py
Browse files
app.py
DELETED
|
@@ -1,389 +0,0 @@
|
|
| 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 |
-
|
| 8 |
-
# --- 1. 載入模型與歷史資料 ---
|
| 9 |
-
try:
|
| 10 |
-
le_action = joblib.load('le_action.pkl')
|
| 11 |
-
le_ip = joblib.load('le_ip.pkl')
|
| 12 |
-
|
| 13 |
-
baseline_df = pd.read_csv('baseline_logs.csv')
|
| 14 |
-
baseline_df['timestamp'] = pd.to_datetime(baseline_df['timestamp'])
|
| 15 |
-
|
| 16 |
-
baseline_df['month'] = baseline_df['timestamp'].dt.month
|
| 17 |
-
baseline_df['day'] = baseline_df['timestamp'].dt.day
|
| 18 |
-
baseline_df['hour'] = baseline_df['timestamp'].dt.hour
|
| 19 |
-
|
| 20 |
-
baseline_X = np.column_stack((
|
| 21 |
-
baseline_df['month'].values,
|
| 22 |
-
baseline_df['day'].values,
|
| 23 |
-
baseline_df['hour'].values,
|
| 24 |
-
le_ip.transform(baseline_df['ip_address'].values),
|
| 25 |
-
le_action.transform(baseline_df['action'].values)
|
| 26 |
-
))
|
| 27 |
-
|
| 28 |
-
AI_READY = True
|
| 29 |
-
print("✅ AI 模組與歷史基準資料載入成功!")
|
| 30 |
-
except Exception as e:
|
| 31 |
-
AI_READY = False
|
| 32 |
-
print(f"⚠️ AI 模組載入失敗,請確認檔案。錯誤: {e}")
|
| 33 |
-
|
| 34 |
-
USER_DB = {
|
| 35 |
-
"student": ["1234", "學生", "同學"],
|
| 36 |
-
"admin": ["1234", "管理", "管理員"],
|
| 37 |
-
}
|
| 38 |
-
|
| 39 |
-
log_history = []
|
| 40 |
-
|
| 41 |
-
# --- 3. 核心邏輯與真實 HDBSCAN 異常偵測 ---
|
| 42 |
-
def check_anomaly(ip, action, log_time, overall_w, time_w, ip_w, dev_w):
|
| 43 |
-
if not AI_READY: return "success"
|
| 44 |
-
if action in ["login_attempt", "logout"]: return "success"
|
| 45 |
-
|
| 46 |
-
try:
|
| 47 |
-
ow = float(overall_w)
|
| 48 |
-
tw = float(time_w)
|
| 49 |
-
iw = float(ip_w)
|
| 50 |
-
dw = float(dev_w)
|
| 51 |
-
|
| 52 |
-
clean_ip = str(ip).split(" ")[0]
|
| 53 |
-
ip_code = float(le_ip.transform([clean_ip])[0])
|
| 54 |
-
action_code = float(le_action.transform([action])[0])
|
| 55 |
-
|
| 56 |
-
current_time = pd.to_datetime(str(log_time))
|
| 57 |
-
current_month = float(current_time.month)
|
| 58 |
-
current_day = float(current_time.day)
|
| 59 |
-
current_hour = float(current_time.hour)
|
| 60 |
-
|
| 61 |
-
time_multiplier = tw / 100.0
|
| 62 |
-
action_scale = (dw / 100.0) * 100.0
|
| 63 |
-
|
| 64 |
-
scaled_baseline = baseline_X.copy().astype(float)
|
| 65 |
-
scaled_baseline[:, 0] *= time_multiplier * 10.0
|
| 66 |
-
scaled_baseline[:, 1] *= time_multiplier * 0.5
|
| 67 |
-
scaled_baseline[:, 2] *= time_multiplier * 2.0
|
| 68 |
-
scaled_baseline[:, 3] *= (iw / 100.0) * 10.0
|
| 69 |
-
scaled_baseline[:, 4] *= action_scale
|
| 70 |
-
|
| 71 |
-
v_month = current_month * time_multiplier * 10.0
|
| 72 |
-
v_day = current_day * time_multiplier * 0.5
|
| 73 |
-
v_hour = current_hour * time_multiplier * 2.0
|
| 74 |
-
v_ip = ip_code * (iw / 100.0) * 10.0
|
| 75 |
-
v_action = action_code * action_scale
|
| 76 |
-
|
| 77 |
-
new_data_point = np.array([[v_month, v_day, v_hour, v_ip, v_action]], dtype=float)
|
| 78 |
-
|
| 79 |
-
combined_X = np.vstack((scaled_baseline, new_data_point))
|
| 80 |
-
strictness = max(2, int(2 + (ow / 100.0) * 4))
|
| 81 |
-
|
| 82 |
-
# 1. 執行標準 HDBSCAN 找出「相對密度異常」
|
| 83 |
-
# (移除了會引發 sklearn Bug 的 cluster_selection_epsilon 參數)
|
| 84 |
-
model = HDBSCAN(
|
| 85 |
-
min_cluster_size=strictness,
|
| 86 |
-
min_samples=2
|
| 87 |
-
)
|
| 88 |
-
clusters = model.fit_predict(combined_X)
|
| 89 |
-
|
| 90 |
-
if clusters[-1] == -1:
|
| 91 |
-
return "⚠️異常_作息或行為不符"
|
| 92 |
-
|
| 93 |
-
# 2. 🌟 雙重防護:手動計算絕對距離 (完美解決盲點且無 Bug)
|
| 94 |
-
# 找出歷史中同一個系統 (Action) 的操作紀錄
|
| 95 |
-
same_action_mask = (baseline_X[:, 4] == action_code)
|
| 96 |
-
|
| 97 |
-
if np.any(same_action_mask):
|
| 98 |
-
history_points = scaled_baseline[same_action_mask]
|
| 99 |
-
# 計算新行為與歷史同系統行為的歐式距離
|
| 100 |
-
distances = np.linalg.norm(history_points - new_data_point[0], axis=1)
|
| 101 |
-
min_distance = np.min(distances)
|
| 102 |
-
|
| 103 |
-
# 計算絕對容忍門檻
|
| 104 |
-
max_tolerance_distance = time_multiplier * 15.0 + 1.0
|
| 105 |
-
|
| 106 |
-
# 如果最短距離依然大於門檻,強制判定為異常
|
| 107 |
-
if min_distance > max_tolerance_distance:
|
| 108 |
-
return "⚠️異常_作息或行為不符"
|
| 109 |
-
|
| 110 |
-
return "success"
|
| 111 |
-
except Exception as e:
|
| 112 |
-
return f"⚠️系統錯誤: {str(e)}"
|
| 113 |
-
|
| 114 |
-
def record_log(ip, cookie, account, role, action, status, time_mode, custom_time, ow, tw, iw, dw):
|
| 115 |
-
global baseline_X
|
| 116 |
-
if time_mode == "自訂時間 (模擬過去/未來)" and custom_time and str(custom_time).strip() != "":
|
| 117 |
-
log_time = str(custom_time)
|
| 118 |
-
else:
|
| 119 |
-
tw_tz = datetime.timezone(datetime.timedelta(hours=8))
|
| 120 |
-
log_time = datetime.datetime.now(tw_tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 121 |
-
|
| 122 |
-
if status == "success":
|
| 123 |
-
ai_judgment = check_anomaly(ip, action, log_time, ow, tw, iw, dw)
|
| 124 |
-
if ai_judgment != "success": status = ai_judgment
|
| 125 |
-
|
| 126 |
-
new_log = {
|
| 127 |
-
"timestamp": log_time, "ip_address": ip, "cookie_id": cookie,
|
| 128 |
-
"account": account, "role": role, "action": action, "status": status
|
| 129 |
-
}
|
| 130 |
-
log_history.insert(0, new_log)
|
| 131 |
-
|
| 132 |
-
if status == "success" and AI_READY:
|
| 133 |
-
try:
|
| 134 |
-
pd.DataFrame([new_log]).to_csv('baseline_logs.csv', mode='a', header=False, index=False, encoding='utf-8-sig')
|
| 135 |
-
|
| 136 |
-
current_time = pd.to_datetime(str(log_time))
|
| 137 |
-
clean_ip = str(ip).split(" ")[0]
|
| 138 |
-
new_row = np.array([[
|
| 139 |
-
float(current_time.month),
|
| 140 |
-
float(current_time.day),
|
| 141 |
-
float(current_time.hour),
|
| 142 |
-
float(le_ip.transform([clean_ip])[0]),
|
| 143 |
-
float(le_action.transform([action])[0])
|
| 144 |
-
]], dtype=float)
|
| 145 |
-
baseline_X = np.vstack((baseline_X, new_row))
|
| 146 |
-
except Exception as e:
|
| 147 |
-
pass # 略過未見過的動作(如登入)寫入 baseline
|
| 148 |
-
|
| 149 |
-
return pd.DataFrame(log_history)
|
| 150 |
-
|
| 151 |
-
def fast_login(target_account, ip, cookie, time_mode, custom_time, ow, tw, iw, dw):
|
| 152 |
-
role, name = USER_DB[target_account][1], USER_DB[target_account][2]
|
| 153 |
-
df = record_log(ip, cookie, target_account, role, "login_attempt", "success", time_mode, custom_time, ow, tw, iw, dw)
|
| 154 |
-
|
| 155 |
-
welcome_msg = f"**{name}** 歡迎您 | 線上人數: 938 (⚡快速登入模式)"
|
| 156 |
-
is_student = (role == "學生")
|
| 157 |
-
is_admin = (role == "管理")
|
| 158 |
-
|
| 159 |
-
return gr.update(visible=False), gr.update(visible=True), gr.update(visible=is_student), gr.update(visible=is_admin), "", welcome_msg, df, target_account
|
| 160 |
-
|
| 161 |
-
def process_login(ip, cookie, account, password, captcha, time_mode, custom_time, ow, tw, iw, dw):
|
| 162 |
-
valid_captcha = "FEIK"
|
| 163 |
-
def fail_response(msg, df):
|
| 164 |
-
return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), msg, gr.update(), df
|
| 165 |
-
|
| 166 |
-
if account not in USER_DB:
|
| 167 |
-
df = record_log(ip, cookie, account, "Unknown", "login_attempt", "failed_no_account", time_mode, custom_time, ow, tw, iw, dw)
|
| 168 |
-
return fail_response("帳號不存在!", df)
|
| 169 |
-
|
| 170 |
-
role, name = USER_DB[account][1], USER_DB[account][2]
|
| 171 |
-
|
| 172 |
-
if captcha.upper() != valid_captcha:
|
| 173 |
-
df = record_log(ip, cookie, account, role, "login_attempt", "failed_captcha", time_mode, custom_time, ow, tw, iw, dw)
|
| 174 |
-
return fail_response("驗證碼錯誤!", df)
|
| 175 |
-
|
| 176 |
-
if USER_DB[account][0] == password:
|
| 177 |
-
welcome_msg = f"**{name}** 歡迎您 | 線上人數: 938"
|
| 178 |
-
df = record_log(ip, cookie, account, role, "login_attempt", "success", time_mode, custom_time, ow, tw, iw, dw)
|
| 179 |
-
is_student = (role == "學生")
|
| 180 |
-
is_admin = (role == "管理")
|
| 181 |
-
|
| 182 |
-
return gr.update(visible=False), gr.update(visible=True), gr.update(visible=is_student), gr.update(visible=is_admin), "", welcome_msg, df
|
| 183 |
-
|
| 184 |
-
df = record_log(ip, cookie, account, role, "login_attempt", "failed_password", time_mode, custom_time, ow, tw, iw, dw)
|
| 185 |
-
return fail_response("密碼錯誤!", df)
|
| 186 |
-
|
| 187 |
-
def simulate_click(ip, cookie, account, button_name, time_mode, custom_time, ow, tw, iw, dw):
|
| 188 |
-
role = USER_DB.get(account, ["", "Unknown"])[1]
|
| 189 |
-
return record_log(ip, cookie, account, role, button_name, "success", time_mode, custom_time, ow, tw, iw, dw)
|
| 190 |
-
|
| 191 |
-
def test_anomaly(ip, cookie, account, action_name, test_time_str, ow, tw, iw, dw):
|
| 192 |
-
role = USER_DB.get(account, ["", "Unknown"])[1]
|
| 193 |
-
return record_log(ip, cookie, account, role, action_name, "success", "自訂時間 (模擬過去/未來)", test_time_str, ow, tw, iw, dw)
|
| 194 |
-
|
| 195 |
-
def logout(ip, cookie, account, time_mode, custom_time, ow, tw, iw, dw):
|
| 196 |
-
role = USER_DB.get(account, ["", "Unknown"])[1]
|
| 197 |
-
df = record_log(ip, cookie, account, role, "logout", "success", time_mode, custom_time, ow, tw, iw, dw)
|
| 198 |
-
return gr.update(visible=True), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), "", "", "", "", df
|
| 199 |
-
|
| 200 |
-
def toggle_time_input(mode):
|
| 201 |
-
return gr.update(visible=(mode == "自訂時間 (模擬過去/未來)"))
|
| 202 |
-
|
| 203 |
-
# --- 4. UI 介面設計 ---
|
| 204 |
-
custom_css = """
|
| 205 |
-
.mock-panel { background-color: var(--background-fill-secondary); padding: 15px; border-radius: 8px; border: 1px dashed var(--border-color-primary); }
|
| 206 |
-
.login-container { max-width: 500px; margin: 0 auto; padding: 20px; }
|
| 207 |
-
.ntut-title { color: #d9534f; font-size: 22px; font-weight: bold; text-align: center; margin-bottom: 20px;}
|
| 208 |
-
.weight-card { padding: 10px; background: white; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); margin-top: 10px; }
|
| 209 |
-
"""
|
| 210 |
-
|
| 211 |
-
with gr.Blocks(title="模擬校園入口與資安防護系統", css=custom_css) as demo:
|
| 212 |
-
with gr.Row():
|
| 213 |
-
with gr.Column(scale=1, elem_classes="mock-panel"):
|
| 214 |
-
gr.Markdown("### ⚙️ 環境變數模擬器")
|
| 215 |
-
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")
|
| 216 |
-
mock_cookie = gr.Textbox(label="模擬 Cookie Session ID", value="sess_baseline")
|
| 217 |
-
gr.Markdown("---")
|
| 218 |
-
time_mode = gr.Radio(label="時間設定模式", choices=["真實時間 (目前時間)", "自訂時間 (模擬過去/未來)"], value="真實時間 (目前時間)")
|
| 219 |
-
custom_time_input = gr.Textbox(label="輸入自訂時間", placeholder="格式: YYYY-MM-DD HH:MM:SS", value="2026-03-17 03:00:00", visible=False)
|
| 220 |
-
gr.Markdown("---")
|
| 221 |
-
gr.Markdown("### 📊 即時 Log 與 AI 判定區")
|
| 222 |
-
log_display = gr.Dataframe(headers=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"], datatype=["str", "str", "str", "str", "str", "str", "str"], interactive=False, wrap=True)
|
| 223 |
-
|
| 224 |
-
with gr.Column(scale=2):
|
| 225 |
-
with gr.Column(visible=True, elem_classes="login-container") as login_view:
|
| 226 |
-
gr.Markdown("<div class='ntut-title'>校園入口網站 Taipei Tech Portal</div>")
|
| 227 |
-
login_msg = gr.Markdown(value="", visible=True)
|
| 228 |
-
with gr.Row(): acc_input = gr.Textbox(label="使用者帳號 (Account)", placeholder="student or admin")
|
| 229 |
-
with gr.Row(): pwd_input = gr.Textbox(label="使用者密碼 (Password)", type="password", placeholder="password : 1234")
|
| 230 |
-
with gr.Row(): gr.HTML("<div style='background:var(--background-fill-secondary); color:var(--body-text-color); padding:10px; font-weight:bold; letter-spacing: 3px; border:1px solid var(--border-color-primary); text-align:center;'>F E I K</div>")
|
| 231 |
-
with gr.Row(): captcha_input = gr.Textbox(label="請輸入驗證碼 (Keyin Code)")
|
| 232 |
-
login_btn = gr.Button("登入 Login", variant="primary")
|
| 233 |
-
|
| 234 |
-
gr.Markdown("---")
|
| 235 |
-
gr.Markdown("<div style='text-align:center; color:gray; font-size: 0.9em;'>🛠️ 開發與測試專用捷徑</div>")
|
| 236 |
-
with gr.Row():
|
| 237 |
-
btn_fast_student = gr.Button("🚀 快速登入 (學生)", variant="secondary")
|
| 238 |
-
btn_fast_admin = gr.Button("🚀 快速登入 (管理員)", variant="secondary")
|
| 239 |
-
|
| 240 |
-
with gr.Column(visible=False) as dashboard_view:
|
| 241 |
-
with gr.Row():
|
| 242 |
-
gr.Markdown("### 資訊系統")
|
| 243 |
-
welcome_text = gr.Markdown(value="", elem_classes="text-right")
|
| 244 |
-
logout_btn = gr.Button("登出", size="sm")
|
| 245 |
-
gr.Markdown("---")
|
| 246 |
-
|
| 247 |
-
with gr.Column(visible=False) as student_view:
|
| 248 |
-
btn_switch_admin = gr.Button("🔄 快速切換為管理員 (Admin) 視角", size="sm", variant="secondary")
|
| 249 |
-
with gr.Accordion("▼ 1. 教務系統", open=True):
|
| 250 |
-
with gr.Row(): btn_eval = gr.Button("▶ 期末網路教學評量", size="sm"); btn_pre_select = gr.Button("▶ 期末網路預選系統", size="sm"); btn_add_drop = gr.Button("▶ 開學後加退選系統", size="sm")
|
| 251 |
-
with gr.Row(): btn_istudy = gr.Button("▶ 北科i學園PLUS", size="sm"); btn_card = gr.Button("▶ 學生證掛失及補發系統", size="sm"); btn_course = gr.Button("▶ 課程系統", size="sm")
|
| 252 |
-
with gr.Row(): btn_score = gr.Button("▶ 學業成績查詢系統", size="sm")
|
| 253 |
-
with gr.Accordion("▼ 2. 學務系統", open=True):
|
| 254 |
-
with gr.Row(): btn_leave = gr.Button("▶ 學生請假系統", size="sm"); btn_dorm = gr.Button("▶ 學生宿舍登錄(抽籤)系統", size="sm"); btn_scholarship = gr.Button("▶ 獎助學金申請系統", size="sm")
|
| 255 |
-
with gr.Accordion("▼ 3. 資訊服務", open=True):
|
| 256 |
-
with gr.Row(): btn_webmail = gr.Button("▶ 網路郵局 WebMail", size="sm"); btn_vdesk = gr.Button("▶ 北科軟體雲", size="sm")
|
| 257 |
-
with gr.Accordion("▼ 惡意操作測試區", open=True):
|
| 258 |
-
btn_hack_score = gr.Button("💀 嘗試偷改成績 (SQL Injection)", variant="stop", size="sm")
|
| 259 |
-
|
| 260 |
-
with gr.Column(visible=False) as admin_view:
|
| 261 |
-
btn_switch_student = gr.Button("🔄 快速切換為學生 (Student) 視角", size="sm", variant="secondary")
|
| 262 |
-
with gr.Accordion("▼ 防護強度微調 (AI 敏感度)", open=True, elem_classes="weight-card"):
|
| 263 |
-
gr.Markdown("<span style='color:gray; font-size:0.9em;'>手動輸入 0~100 的數值。提高強度會增加誤報率,但能更有效攔截新型攻擊。</span>")
|
| 264 |
-
with gr.Row():
|
| 265 |
-
overall_weight = gr.Number(label="總體防護強度 (%)", value=75, minimum=0, maximum=100)
|
| 266 |
-
time_weight = gr.Number(label="時間特徵權重 (%)", value=80, minimum=0, maximum=100)
|
| 267 |
-
with gr.Row():
|
| 268 |
-
ip_weight = gr.Number(label="IP 聲譽權重 (%)", value=65, minimum=0, maximum=100)
|
| 269 |
-
device_weight = gr.Number(label="裝置指紋/行為權重 (%)", value=45, minimum=0, maximum=100)
|
| 270 |
-
|
| 271 |
-
with gr.Accordion("▼ HDBSCAN 異常辨識自動化測��區", open=True, elem_classes="weight-card"):
|
| 272 |
-
gr.Markdown("<span style='color:gray; font-size:0.9em;'>點擊按鈕將直接以指定時間點執行該系統的操作,結果將顯示於左側 Log 區。</span>")
|
| 273 |
-
|
| 274 |
-
gr.Markdown("#### 1. 選課相關系統 (具備強烈季節性)")
|
| 275 |
-
with gr.Row():
|
| 276 |
-
t_pre_sel_norm = gr.Button("✅ 正常: 初選系統 (06-10 22:00)", size="sm")
|
| 277 |
-
t_pre_sel_anom = gr.Button("⚠️ 異常: 初選系統 (10-15 14:00)", size="sm")
|
| 278 |
-
with gr.Row():
|
| 279 |
-
t_course_norm = gr.Button("✅ 正常: 選課系統 (02-15 16:00)", size="sm")
|
| 280 |
-
t_course_anom = gr.Button("⚠️ 異常: 選課系統 (05-20 09:00)", size="sm")
|
| 281 |
-
with gr.Row():
|
| 282 |
-
t_add_drop_norm = gr.Button("✅ 正常: 加退選系統 (09-15 08:00)", size="sm")
|
| 283 |
-
t_add_drop_anom = gr.Button("⚠️ 異常: 加退選系統 (04-10 21:00)", size="sm")
|
| 284 |
-
|
| 285 |
-
gr.Markdown("#### 2. 期末與成績相關 (具備週期性)")
|
| 286 |
-
with gr.Row():
|
| 287 |
-
t_eval_norm = gr.Button("✅ 正常: 教學評鑑 (12-20 23:00)", size="sm")
|
| 288 |
-
t_eval_anom = gr.Button("⚠️ 異常: 教學評鑑 (03-05 11:00)", size="sm")
|
| 289 |
-
with gr.Row():
|
| 290 |
-
t_score_norm = gr.Button("✅ 正常: 成績查詢 (04-20 11:00)", size="sm")
|
| 291 |
-
t_score_anom = gr.Button("⚠️ 異常: 成績查詢 (08-15 10:00)", size="sm")
|
| 292 |
-
|
| 293 |
-
gr.Markdown("#### 3. 校務與行政服務 (生活與常規)")
|
| 294 |
-
with gr.Row():
|
| 295 |
-
t_dorm_norm = gr.Button("✅ 正常: 宿舍系統 (07-25 16:00)", size="sm")
|
| 296 |
-
t_dorm_anom = gr.Button("⚠️ 異常: 宿舍系統 (11-15 14:00)", size="sm")
|
| 297 |
-
with gr.Row():
|
| 298 |
-
t_schol_norm = gr.Button("✅ 正常: 獎學金申請 (03-15 12:00)", size="sm")
|
| 299 |
-
t_schol_anom = gr.Button("⚠️ 異常: 獎學金申請 (08-10 05:00)", size="sm")
|
| 300 |
-
with gr.Row():
|
| 301 |
-
t_card_norm = gr.Button("✅ 正常: 學生證掛失 (任何月份 16:00)", size="sm")
|
| 302 |
-
t_card_anom = gr.Button("⚠️ 異常: 學生證掛失 (任何月份 04:00)", size="sm")
|
| 303 |
-
|
| 304 |
-
gr.Markdown("#### 4. 學習與日常輔助系統 (具備作息規律)")
|
| 305 |
-
with gr.Row():
|
| 306 |
-
t_istudy_norm = gr.Button("✅ 正常: iStudy 平台 (03-20 13:00)", size="sm")
|
| 307 |
-
t_istudy_anom = gr.Button("⚠️ 異常: iStudy 平台 (06-29 03:00)", size="sm")
|
| 308 |
-
with gr.Row():
|
| 309 |
-
t_leave_norm = gr.Button("✅ 正常: 請假系統 (10-05 08:00)", size="sm")
|
| 310 |
-
t_leave_anom = gr.Button("⚠️ 異常: 請假系統 (週日 02:00)", size="sm")
|
| 311 |
-
with gr.Row():
|
| 312 |
-
t_vdesk_norm = gr.Button("✅ 正常: 軟體雲/信箱 (11-10 10:00)", size="sm")
|
| 313 |
-
t_vdesk_anom = gr.Button("⚠️ 異常: 軟體雲/信箱 (深夜 04:00)", size="sm")
|
| 314 |
-
|
| 315 |
-
# --- 綁定事件 ---
|
| 316 |
-
time_mode.change(fn=toggle_time_input, inputs=time_mode, outputs=custom_time_input)
|
| 317 |
-
|
| 318 |
-
weight_inputs = [overall_weight, time_weight, ip_weight, device_weight]
|
| 319 |
-
|
| 320 |
-
login_btn.click(
|
| 321 |
-
fn=process_login,
|
| 322 |
-
inputs=[mock_ip, mock_cookie, acc_input, pwd_input, captcha_input, time_mode, custom_time_input] + weight_inputs,
|
| 323 |
-
outputs=[login_view, dashboard_view, student_view, admin_view, login_msg, welcome_text, log_display]
|
| 324 |
-
)
|
| 325 |
-
logout_btn.click(
|
| 326 |
-
fn=logout,
|
| 327 |
-
inputs=[mock_ip, mock_cookie, acc_input, time_mode, custom_time_input] + weight_inputs,
|
| 328 |
-
outputs=[login_view, dashboard_view, student_view, admin_view, acc_input, pwd_input, captcha_input, login_msg, log_display]
|
| 329 |
-
)
|
| 330 |
-
|
| 331 |
-
fast_inputs = [mock_ip, mock_cookie, time_mode, custom_time_input] + weight_inputs
|
| 332 |
-
fast_outputs = [login_view, dashboard_view, student_view, admin_view, login_msg, welcome_text, log_display, acc_input]
|
| 333 |
-
|
| 334 |
-
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)
|
| 335 |
-
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)
|
| 336 |
-
btn_switch_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)
|
| 337 |
-
btn_switch_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)
|
| 338 |
-
|
| 339 |
-
action_mapping = [
|
| 340 |
-
(btn_eval, "click_eval_system"), (btn_pre_select, "click_pre_select_system"),
|
| 341 |
-
(btn_add_drop, "click_add_drop_system"), (btn_istudy, "click_istudy"),
|
| 342 |
-
(btn_card, "click_card_loss"), (btn_course, "click_course_system"),
|
| 343 |
-
(btn_score, "click_score_query"), (btn_leave, "click_leave_system"),
|
| 344 |
-
(btn_dorm, "click_dorm_system"), (btn_scholarship, "click_scholarship"),
|
| 345 |
-
(btn_webmail, "click_webmail"), (btn_vdesk, "click_vdesk"),
|
| 346 |
-
(btn_hack_score, "malicious_sql_injection")
|
| 347 |
-
]
|
| 348 |
-
|
| 349 |
-
for btn, action_name in action_mapping:
|
| 350 |
-
btn.click(
|
| 351 |
-
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),
|
| 352 |
-
inputs=[mock_ip, mock_cookie, acc_input, time_mode, custom_time_input] + weight_inputs,
|
| 353 |
-
outputs=[log_display]
|
| 354 |
-
)
|
| 355 |
-
|
| 356 |
-
test_mapping = [
|
| 357 |
-
(t_pre_sel_norm, "click_pre_select_system", "2026-06-10 22:00:00"),
|
| 358 |
-
(t_pre_sel_anom, "click_pre_select_system", "2026-10-15 14:00:00"),
|
| 359 |
-
(t_course_norm, "click_course_system", "2026-02-15 16:00:00"),
|
| 360 |
-
(t_course_anom, "click_course_system", "2026-05-20 09:00:00"),
|
| 361 |
-
(t_add_drop_norm, "click_add_drop_system", "2026-09-15 08:00:00"),
|
| 362 |
-
(t_add_drop_anom, "click_add_drop_system", "2026-04-10 21:00:00"),
|
| 363 |
-
(t_eval_norm, "click_eval_system", "2026-12-20 23:00:00"),
|
| 364 |
-
(t_eval_anom, "click_eval_system", "2026-03-05 11:00:00"),
|
| 365 |
-
(t_score_norm, "click_score_query", "2026-04-20 11:00:00"),
|
| 366 |
-
(t_score_anom, "click_score_query", "2026-08-15 10:00:00"),
|
| 367 |
-
(t_dorm_norm, "click_dorm_system", "2026-07-25 16:00:00"),
|
| 368 |
-
(t_dorm_anom, "click_dorm_system", "2026-11-15 14:00:00"),
|
| 369 |
-
(t_schol_norm, "click_scholarship", "2026-03-15 12:00:00"),
|
| 370 |
-
(t_schol_anom, "click_scholarship", "2026-08-10 05:00:00"),
|
| 371 |
-
(t_card_norm, "click_card_loss", "2026-10-01 16:00:00"),
|
| 372 |
-
(t_card_anom, "click_card_loss", "2026-10-01 04:00:00"),
|
| 373 |
-
(t_istudy_norm, "click_istudy", "2026-03-20 13:00:00"),
|
| 374 |
-
(t_istudy_anom, "click_istudy", "2026-06-29 03:00:00"),
|
| 375 |
-
(t_leave_norm, "click_leave_system", "2026-10-05 08:00:00"),
|
| 376 |
-
(t_leave_anom, "click_leave_system", "2026-10-11 02:00:00"),
|
| 377 |
-
(t_vdesk_norm, "click_vdesk", "2026-11-10 10:00:00"),
|
| 378 |
-
(t_vdesk_anom, "click_vdesk", "2026-11-10 04:00:00")
|
| 379 |
-
]
|
| 380 |
-
|
| 381 |
-
for btn, action_name, test_time_str in test_mapping:
|
| 382 |
-
btn.click(
|
| 383 |
-
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),
|
| 384 |
-
inputs=[mock_ip, mock_cookie, acc_input, overall_weight, time_weight, ip_weight, device_weight],
|
| 385 |
-
outputs=[log_display]
|
| 386 |
-
)
|
| 387 |
-
|
| 388 |
-
if __name__ == "__main__":
|
| 389 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|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