add chart
Browse files7 unmodified lines8910111213141516171819206 unmodified lines2728293031323334353637383940414223 unmodified lines666768697071727374757677787980818283848586878889909192939431 unmodified lines12612712812913013113220 unmodified lines15315415515615715815977 unmodified lines23723823924024124224316 unmodified lines26026126226326426526619 unmodified lines28628728828929029129229329429529629729829930030170 unmodified lines3723733743753763773783793803813823833843853863873883894 unmodified lines3943953963973983994004014024031 unmodified line4054064074084094104114124134144154164174184194202 unmodified lines42342442542642742842943043143243357 unmodified lines49149249349449549649749849950052 unmodified lines5535545555565575585595605615625635645655665677 unmodified linesimport os# --- 🌟 新增:全域統計狀態變數 ---# 用於快取統計數據,避免每分鐘重新讀取 CSV 檔案造成效能瓶頸global_stats = {"total_count": 0,"abnormal_count": 0,"start_time": datetime.datetime.now()}# 初始化歷史日誌串列log_history = []initial_df_abn = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])6 unmodified linesbaseline_df = pd.read_csv('baseline_logs.csv')baseline_df['timestamp'] = pd.to_datetime(baseline_df['timestamp'])# 🌟 修改:初始化全域統計數據global_stats["total_count"] = len(baseline_df)# 統計歷史紀錄中包含「異常」字眼的 Log 數量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']}")# 🌟 保持:預載歷史日誌顯示log_history = baseline_df.sort_values(by='timestamp', ascending=False).head(20).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)23 unmodified lines"admin": ["1234", "管理", "管理員"],}# --- 🌟 新增:儀表板 HTML 生成函式 (每分鐘呼叫) ---def get_dashboard_html():total = global_stats["total_count"]abnormal = global_stats["abnormal_count"]# 計算異常率rate = (abnormal / total * 100) if total > 0 else 0# 決定系統狀態符號與顏色if not AI_READY:status_icon = "🔴"status_text = "系統錯誤"status_color = "#ef4444" # Redstatus_desc = "AI 模型載入失敗,防護停用中。"elif rate > 10: # 假設異常率大於 10% 顯示警告status_icon = "🟡"status_text = "高風險警告"status_color = "#f59e0b" # Amberstatus_desc = "近期異常行為頻發,請立刻檢查 Log。"else:status_icon = "🟢"status_text = "正常執行"status_color = "#10b981" # Greenstatus_desc = "HDBSCAN 與 Agent 服務運作正常。"html = f"""31 unmodified lines"""return html# --- 🌟 新增/修改:Groq AI Agent 呼叫函式 (修正模型名稱) ---def explain_abnormal_log(log_text):if not log_text or log_text.strip() == "":return "⚠️ 請先提供異常 Log 資訊以進行分析。"20 unmodified lines"content": f"請分析這筆異常 Log:\n{log_text}"}],# 🌟 修正:更換為 Groq 目前支援的 llama3 模型,避免 decommissioned 錯誤model="llama-3.1-8b-instant",temperature=0.5,max_tokens=30077 unmodified linesexcept Exception as e:return f"⚠️系統錯誤: {str(e)}"# 🌟 修改:record_log 函式,確保數據即時累加到統計變數中def record_log(ip, cookie, account, role, action, status, time_mode, custom_time, ow, tw, iw, dw):global baseline_Xif time_mode == "自訂時間 (模擬過去/未來)" and custom_time and str(custom_time).strip() != "":16 unmodified linesexcept Exception as e:print(f"⚠️ 外部日誌推送失敗: {e}")# 🌟 修改:更新全域統計計數器 (即時)global_stats["total_count"] += 1if "異常" in str(status):global_stats["abnormal_count"] += 119 unmodified linesdf_all = pd.DataFrame(log_history)# 擷取異常清單abnormal_logs = [log for log in log_history if "異常" in str(log.get("status", ""))]df_abnormal = pd.DataFrame(abnormal_logs) if abnormal_logs else pd.DataFrame(columns=df_all.columns)# 若有新異常,自動覆寫輸入框if "異常" in str(status):latest_str = f"時間: {log_time} | IP: {ip} | 帳號: {account} | 動作: {action} | 狀態: {status}"input_update = gr.update(value=latest_str)else:input_update = gr.update() # 正常行為則不干涉使用者手動輸入的內容return df_all, df_abnormal, input_update70 unmodified lines}.stat-card {flex: 1;background-color: #ffffff !important; /* 強制卡片底色為白色 */padding: 15px;border-radius: 10px;box-shadow: 0 4px 6px rgba(0,0,0,0.05);display: flex;align-items: center;gap: 15px;border-top: 4px solid transparent; /* 用於狀態卡的頂部顏色 */}.card-total { border-left: 4px solid #10b981; } /* Green left border */.card-anomaly { border-left: 4px solid #ef4444; } /* Red left border */.card-status { border-left: 4px solid #3b82f6; } /* Blue left border */.card-icon {font-size: 30px;4 unmodified linesflex: 1;}.card-label {color: #374151 !important; /* 強制標題文字為深灰色 */font-size: 13px;margin-bottom: 2px;font-weight: bold !important;}.card-value-container {display: flex;1 unmodified linegap: 8px;}.card-value {font-size: 24px;font-weight: bold;}/* 針對「總監測量」的數字強制設為黑色,不影響異常率與狀態的專屬顏色 */.card-total .card-value {color: #000000 !important;}.card-unit {font-size: 14px;color: #4b5563 !important; /* 強制單位文字為深灰色 */font-weight: normal;}.card-trend {2 unmodified linesborder-radius: 4px;}.trend-up {background-color: #fee2e2 !important;color: #ef4444 !important;}.card-sub-text {color: #6b7280 !important; /* 強制副標題說明文字為中灰色 */font-size: 11px;margin-top: 2px;}57 unmodified lineswith gr.Tab("🛡️ 管理員專區", id="admin_tab"):# 🌟 新增:統計儀表板 HTML 元件,放置於最上方# 初始化時呼叫 get_dashboard_html() 生成內容stat_dashboard_display = gr.HTML(value=get_dashboard_html())with gr.Accordion("▼ 防護強度微調 (AI 敏感度)", open=True, elem_classes="weight-card"):gr.Markdown("<span style='color:gray; font-size:0.9em;'>手動輸入 0~100 的數值。提高強度會增加誤報率,但能更有效攔截新型攻擊。</span>")with gr.Row():52 unmodified lines# --- 綁定事件 ---# 🌟 新增:設定定時刷新邏輯。當頁面載入時,啟動計時器,每 60 秒呼叫 get_dashboard_html 更新 stat_dashboard_display# A. 網頁剛載入時,先手動執行一次生成儀表板demo.load(fn=get_dashboard_html, inputs=None, outputs=stat_dashboard_display)# B. 之後每 60 秒,讓 Timer 去觸發更新dashboard_timer.tick(fn=get_dashboard_html, inputs=None, outputs=stat_dashboard_display)time_mode.change(fn=toggle_time_input, inputs=time_mode, outputs=custom_time_input)# 🌟 保持:綁定 AI 分析按鈕btn_explain_log.click(fn=explain_abnormal_log, inputs=[abnormal_log_input], outputs=[ai_explanation_output])weight_inputs = [overall_weight, time_weight, ip_weight, device_weight]7 unmodified lines891011121314151617181920212223242526272829303132333435366 unmodified lines43444546474849505152535423 unmodified lines7879808182838485868788899091929394959697989910010110210310431 unmodified lines13613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117220 unmodified lines19319419519619719877 unmodified lines27627727827928028128216 unmodified lines29930030130230330419 unmodified lines32432532632732832933033133233333433533633770 unmodified lines4084094104114124134144154164174184194204214224234244254 unmodified lines4304314324334344354364374381 unmodified line4404414424434444454464474484494504514522 unmodified lines45545645745845946046146246346446557 unmodified lines52352452552652752852953053153253353453553653753853954054154254354454554654754854955055152 unmodified lines6046056066076086096106116126136146156166176187 unmodified linesimport os# --- 🌟 新增:全域統計狀態變數 ---global_stats = {"total_count": 0,"abnormal_count": 0,"start_time": datetime.datetime.now()}# --- 🌟 新增:13 個系統按鈕的對應字典,供下拉選單使用 ---ACTION_MAP = {"教務系統: 期末網路教學評量": "click_eval_system","教務系統: 期末網路預選系統": "click_pre_select_system","教務系統: 開學後加退選系統": "click_add_drop_system","教務系統: 北科i學園PLUS": "click_istudy","教務系統: 學生證掛失及補發系統": "click_card_loss","教務系統: 課程系統": "click_course_system","教務系統: 學業成績查詢系統": "click_score_query","學務系統: 學生請假系統": "click_leave_system","學務系統: 學生宿舍登錄(抽籤)系統": "click_dorm_system","學務系統: 獎助學金申請系統": "click_scholarship","資訊服務: 網路郵局 WebMail": "click_webmail","資訊服務: 北科軟體雲": "click_vdesk","惡意測試: 嘗試偷改成績 (SQL Injection)": "malicious_sql_injection"}# 初始化歷史日誌串列log_history = []initial_df_abn = pd.DataFrame(columns=["timestamp", "ip_address", "cookie_id", "account", "role", "action", "status"])6 unmodified linesbaseline_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']}")log_history = baseline_df.sort_values(by='timestamp', ascending=False).head(20).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)23 unmodified lines"admin": ["1234", "管理", "管理員"],}# --- 🌟 儀表板 HTML 生成函式 ---def get_dashboard_html():total = global_stats["total_count"]abnormal = global_stats["abnormal_count"]rate = (abnormal / total * 100) if total > 0 else 0if not AI_READY:status_icon = "🔴"status_text = "系統錯誤"status_color = "#ef4444"status_desc = "AI 模型載入失敗,防護停用中。"elif rate > 10:status_icon = "🟡"status_text = "高風險警告"status_color = "#f59e0b"status_desc = "近期異常行為頻發,請立刻檢查 Log。"else:status_icon = "🟢"status_text = "正常執行"status_color = "#10b981"status_desc = "HDBSCAN 與 Agent 服務運作正常。"html = f"""31 unmodified lines"""return html# --- 🌟 新增:散佈圖圖表資料生成函式 ---def get_scatter_data(selected_key):# 若使用者尚未選擇下拉選單,回傳空表讓畫布留白if not selected_key:return pd.DataFrame(columns=["timestamp", "time_of_day", "status", "ip_address", "account"])action_code = ACTION_MAP.get(selected_key)try:df = pd.read_csv('baseline_logs.csv')df['timestamp'] = pd.to_datetime(df['timestamp'])# 僅保留下拉選單指定的動作紀錄df = df[df['action'] == action_code].copy()if df.empty:return pd.DataFrame(columns=["timestamp", "time_of_day", "status", "ip_address", "account"])# 🌟 轉換時間為 0~23.99 的小數 (作為 Y 軸)# 範例:早上 06:30 會變成 6 + 30/60 = 6.5df['time_of_day'] = df['timestamp'].dt.hour + df['timestamp'].dt.minute / 60.0return dfexcept Exception as e:print(f"圖表資料讀取失敗: {e}")return pd.DataFrame(columns=["timestamp", "time_of_day", "status", "ip_address", "account"])# --- 🌟 新增:定時器觸發同步更新 (同時更新儀表板與圖表) ---def timer_update(selected_key):return get_dashboard_html(), get_scatter_data(selected_key)# --- Groq AI Agent 呼叫函式 ---def explain_abnormal_log(log_text):if not log_text or log_text.strip() == "":return "⚠️ 請先提供異常 Log 資訊以進行分析。"20 unmodified lines"content": f"請分析這筆異常 Log:\n{log_text}"}],model="llama-3.1-8b-instant",temperature=0.5,max_tokens=30077 unmodified linesexcept Exception as e:return f"⚠️系統錯誤: {str(e)}"# record_log 函式def record_log(ip, cookie, account, role, action, status, time_mode, custom_time, ow, tw, iw, dw):global baseline_Xif time_mode == "自訂時間 (模擬過去/未來)" and custom_time and str(custom_time).strip() != "":16 unmodified linesexcept Exception as e:print(f"⚠️ 外部日誌推送失敗: {e}")global_stats["total_count"] += 1if "異常" in str(status):global_stats["abnormal_count"] += 119 unmodified linesdf_all = pd.DataFrame(log_history)abnormal_logs = [log for log in log_history if "異常" in str(log.get("status", ""))]df_abnormal = pd.DataFrame(abnormal_logs) if abnormal_logs else pd.DataFrame(columns=df_all.columns)if "異常" in str(status):latest_str = f"時間: {log_time} | IP: {ip} | 帳號: {account} | 動作: {action} | 狀態: {status}"input_update = gr.update(value=latest_str)else:input_update = gr.update()return df_all, df_abnormal, input_update70 unmodified lines}.stat-card {flex: 1;background: white;padding: 15px;border-radius: 10px;box-shadow: 0 4px 6px rgba(0,0,0,0.05);display: flex;align-items: center;gap: 15px;border-top: 4px solid transparent;}.card-total { border-left: 4px solid #10b981; }.card-anomaly { border-left: 4px solid #ef4444; }.card-status { border-left: 4px solid #3b82f6; }.card-icon {font-size: 30px;4 unmodified linesflex: 1;}.card-label {color: #6b7280;font-size: 13px;margin-bottom: 2px;}.card-value-container {display: flex;1 unmodified linegap: 8px;}.card-value {color: #1f2937;font-size: 24px;font-weight: bold;}.card-unit {font-size: 14px;color: #6b7280;font-weight: normal;}.card-trend {2 unmodified linesborder-radius: 4px;}.trend-up {background-color: #fee2e2;color: #ef4444;}.card-sub-text {color: #9ca3af;font-size: 11px;margin-top: 2px;}57 unmodified lineswith gr.Tab("🛡️ 管理員專區", id="admin_tab"):stat_dashboard_display = gr.HTML(value=get_dashboard_html())# 🌟 新增:系統操作時間分佈圖與下拉選單with gr.Accordion("▼ 系統操作時間分佈圖 (即時監控)", open=True, elem_classes="weight-card"):gr.Markdown("<span style='color:gray; font-size:0.9em;'>選擇下方系統以檢視該系統在歷史��即時紀錄中的時間分佈狀況。圖表每分鐘會自動同步更新。</span>")action_dropdown = gr.Dropdown(choices=list(ACTION_MAP.keys()),label="選擇要檢視的系統資料分佈",value=None)# 由於 X 軸為日期,Y 軸為 0~24 的時間小數,能精確看出異常點落在哪個深夜或非活動時間action_plot = gr.ScatterPlot(value=None,x="timestamp",y="time_of_day",color="status",tooltip=["timestamp", "time_of_day", "ip_address", "account", "status"],x_title="年份與日期",y_title="一天中的時間點 (0.0 ~ 23.99小時)",title="使用者行為操作時間點分析",height=400)with gr.Accordion("▼ 防護強度微調 (AI 敏感度)", open=True, elem_classes="weight-card"):gr.Markdown("<span style='color:gray; font-size:0.9em;'>手動輸入 0~100 的數值。提高強度會增加誤報率,但能更有效攔截新型攻擊。</span>")with gr.Row():52 unmodified lines# --- 綁定事件 ---# 🌟 綁定:網頁剛載入與每分鐘定時器都會更新「儀表板 + 散佈圖」demo.load(fn=timer_update, inputs=[action_dropdown], outputs=[stat_dashboard_display, action_plot])dashboard_timer.tick(fn=timer_update, inputs=[action_dropdown], outputs=[stat_dashboard_display, action_plot])# 🌟 綁定:使用者更換下拉選單時,立刻更新散佈圖action_dropdown.change(fn=get_scatter_data, inputs=[action_dropdown], outputs=[action_plot])time_mode.change(fn=toggle_time_input, inputs=time_mode, outputs=custom_time_input)btn_explain_log.click(fn=explain_abnormal_log, inputs=[abnormal_log_input], outputs=[ai_explanation_output])weight_inputs = [overall_weight, time_weight, ip_weight, device_weight]
app.py+93-42