Spaces:
Sleeping
Sleeping
dynamic history data
Browse files51 unmodified lines525354555657585960616263646566676869707172737411 unmodified lines8687888990919223 unmodified lines116117118119120121122333 unmodified lines4564574584594604614629 unmodified lines472473474475476477478106 unmodified lines5855865875885895905918 unmodified lines60060160260360460560629 unmodified lines63663763863964064164214 unmodified lines65765865966066166266351 unmodified lineslog_history = []initial_df_abn = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])# --- 1. 載入模型與歷史資料 ---try:le_action = joblib.load('le_action.pkl')le_ip = joblib.load('le_ip.pkl')baseline_df = pd.read_csv('baseline_logs.csv')baseline_df['timestamp'] = pd.to_datetime(baseline_df['timestamp'])global_stats["total_count"] = len(baseline_df)global_stats["abnormal_count"] = baseline_df[baseline_df['status'].str.contains("異常", na=False)].shape[0]print(f"📊 統計初始化:總監測量 {global_stats['total_count']}, 異常數 {global_stats['abnormal_count']}")# 🌟 修正點 1:將 Timestamp 強制轉為字串,避免前端 JS 崩潰卡讀取display_df = baseline_df.sort_values(by='timestamp', ascending=False).head(20).copy()display_df['timestamp'] = display_df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')log_history = display_df.to_dict('records')initial_abnormal_logs = [log for log in log_history if "異常" in str(log.get("status", ""))]if initial_abnormal_logs:initial_df_abn = pd.DataFrame(initial_abnormal_logs)11 unmodified lines))AI_READY = Trueprint("✅ AI 模組與歷史基準資料載入成功!")except Exception as e:AI_READY = Falseglobal_stats["total_count"] = 023 unmodified lines<div class="stat-card card-total"><div class="card-icon">📊</div><div class="card-content"><div class="card-label">總監測量 (預警流量)</div><div class="card-value">{total:,} <span class="card-unit">筆 Log</span></div><div class="card-sub-text">自系統啟動起統計 (+今日即時)</div></div>333 unmodified lineswith gr.Blocks(title="模擬校園入口與資安防護系統") as demo:# 🌟 修正點 2:建立隱形的 State,作為 Dataframe 的獨立資料載體 (解耦)store_df_all = gr.State(value=pd.DataFrame(log_history))store_df_abn = gr.State(value=initial_df_abn)9 unmodified linescustom_time_input = gr.Textbox(label="輸入自訂時間", placeholder="格式: YYYY-MM-DD HH:MM:SS", value="2026-03-17 03:00:00", visible=False)gr.Markdown("---")gr.Markdown("### 📊 即時 Log 與 AI 判定區")# 🌟 指定吃 Pandas Dataframe 以維持最穩定的序列化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)with gr.Column(scale=2):106 unmodified lineswith gr.Row():t_vdesk_norm = gr.Button("✅ 正常: 軟體雲/WebMail (03-22 18:00)", size="sm"); t_vdesk_anom = gr.Button("⚠️ 異常: 軟體雲/WebMail (08-10 00:00)", size="sm")# --- 🌟 修正點 3:綁定 State 更新到實體的 Dataframe (確保 DOM 渲染完畢後才餵入資料) ---def update_dataframes(df_all, df_abn):return gr.update(value=df_all), gr.update(value=df_abn)8 unmodified linesweight_inputs = [overall_weight, time_weight, ip_weight, device_weight]# 🎯 把輸出目標從實體 Dataframe 改為背後的 Stateupdate_outputs = [main_router, role_tabs, login_msg, welcome_text, store_df_all, store_df_abn, abnormal_log_input]login_btn.click(29 unmodified linesbtn.click(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),inputs=[mock_ip, mock_cookie, acc_input, time_mode, custom_time_input] + weight_inputs,outputs=[store_df_all, store_df_abn, abnormal_log_input] # 🎯 同步改為輸出給 State)test_mapping = [14 unmodified linesbtn.click(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),inputs=[mock_ip, mock_cookie, acc_input, overall_weight, time_weight, ip_weight, device_weight],outputs=[store_df_all, store_df_abn, abnormal_log_input] # 🎯 同步改為輸出給 State)if __name__ == "__main__":51 unmodified lines52535455565758596061626364656667686970717273747576777879808182838411 unmodified lines9697989910010110223 unmodified lines126127128129130131132333 unmodified lines4664674684694704714729 unmodified lines482483484485486487106 unmodified lines5945955965975985998 unmodified lines60860961061161261329 unmodified lines64364464564664764864914 unmodified lines66466566666766866967051 unmodified lineslog_history = []initial_df_abn = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])# --- 1. 載入模型與歷史資料 (結合 logger_service 雲端同步) ---try:le_action = joblib.load('le_action.pkl')le_ip = joblib.load('le_ip.pkl')# 🌟 核心升級:啟動時直接從 Hugging Face 雲端拉取最新動態歷史資料庫print("🔄 正在從 Hugging Face 雲端同步最新動態歷史資料...")baseline_df = logger_service.sync_from_hf()# 防呆機制:如果雲端資料庫為空或下載失敗,退回使用本地端檔案if baseline_df.empty and os.path.exists('baseline_logs.csv'):print("⚠️ 雲端資料庫為空或讀取失敗,改用本地端 baseline_logs.csv")baseline_df = pd.read_csv('baseline_logs.csv')baseline_df['timestamp'] = pd.to_datetime(baseline_df['timestamp'])# 這裡的統計數據現在會包含雲端的最新總數與異常數global_stats["total_count"] = len(baseline_df)global_stats["abnormal_count"] = baseline_df[baseline_df['status'].str.contains("異常", na=False)].shape[0]print(f"📊 統計初始化:總監測量 {global_stats['total_count']}, 異常數 {global_stats['abnormal_count']}")# 確保前端表格吃的是正確的字串格式,並且直接抓取雲端最新的 20 筆作為預設顯示display_df = baseline_df.sort_values(by='timestamp', ascending=False).head(20).copy()display_df['timestamp'] = display_df['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S')log_history = display_df.to_dict('records')# 異常清單也會直接從雲端最新的資料中篩選出來initial_abnormal_logs = [log for log in log_history if "異常" in str(log.get("status", ""))]if initial_abnormal_logs:initial_df_abn = pd.DataFrame(initial_abnormal_logs)11 unmodified lines))AI_READY = Trueprint("✅ AI 模組與動態歷史基準資料載入成功!")except Exception as e:AI_READY = Falseglobal_stats["total_count"] = 023 unmodified lines<div class="stat-card card-total"><div class="card-icon">📊</div><div class="card-content"><div class="card-label">總監測量 (包含雲端資料庫)</div><div class="card-value">{total:,} <span class="card-unit">筆 Log</span></div><div class="card-sub-text">自系統啟動起統計 (+今日即時)</div></div>333 unmodified lineswith gr.Blocks(title="模擬校園入口與資安防護系統") as demo:# 確保 State 初始化時能抓到剛從雲端下載的最新資料store_df_all = gr.State(value=pd.DataFrame(log_history))store_df_abn = gr.State(value=initial_df_abn)9 unmodified linescustom_time_input = gr.Textbox(label="輸入自訂時間", placeholder="格式: YYYY-MM-DD HH:MM:SS", value="2026-03-17 03:00:00", visible=False)gr.Markdown("---")gr.Markdown("### 📊 即時 Log 與 AI 判定區")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)with gr.Column(scale=2):106 unmodified lineswith gr.Row():t_vdesk_norm = gr.Button("✅ 正常: 軟體雲/WebMail (03-22 18:00)", size="sm"); t_vdesk_anom = gr.Button("⚠️ 異常: 軟體雲/WebMail (08-10 00:00)", size="sm")def update_dataframes(df_all, df_abn):return gr.update(value=df_all), gr.update(value=df_abn)8 unmodified linesweight_inputs = [overall_weight, time_weight, ip_weight, device_weight]update_outputs = [main_router, role_tabs, login_msg, welcome_text, store_df_all, store_df_abn, abnormal_log_input]login_btn.click(29 unmodified linesbtn.click(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),inputs=[mock_ip, mock_cookie, acc_input, time_mode, custom_time_input] + weight_inputs,outputs=[store_df_all, store_df_abn, abnormal_log_input])test_mapping = [14 unmodified linesbtn.click(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),inputs=[mock_ip, mock_cookie, acc_input, overall_weight, time_weight, ip_weight, device_weight],outputs=[store_df_all, store_df_abn, abnormal_log_input])if __name__ == "__main__":
app.py+18-11