ss900371tw commited on
Commit
2ed836b
·
verified ·
1 Parent(s): ebaaf9c

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +162 -165
src/streamlit_app.py CHANGED
@@ -9,26 +9,31 @@ import uuid
9
  import time
10
  import sys
11
  from typing import List, Dict, Any
 
12
  # === HuggingFace 模型相關套件 (替換為 InferenceClient) ===
13
  try:
14
  from huggingface_hub import InferenceClient
15
  except ImportError:
16
  st.error("請檢查是否安裝了所有 Hugging Face 相關依賴:pip install huggingface-hub")
 
17
  # === LangChain/RAG 相關套件 (保持不變) ===
18
  from langchain_community.embeddings import HuggingFaceEmbeddings
19
  from langchain_core.documents import Document
20
  from langchain_community.vectorstores import FAISS
21
  from langchain_community.vectorstores.utils import DistanceStrategy
22
  from langchain_community.docstore.in_memory import InMemoryDocstore
23
- # 嘗試匯入 pypdf
 
24
  try:
25
  import pypdf
26
  except ImportError:
27
  pypdf = None
 
28
  # --- 頁面設定 ---
29
  st.set_page_config(page_title="Cybersecurity AI Assistant (Hugging Face RAG & IP Correlated Analysis)", page_icon="🛡️", layout="wide")
30
  st.title("🛡️ LLM with FAISS RAG & IP Correlated Analysis (Inference Client)")
31
  st.markdown("已啟用:**IndexFlatIP** + **L2 正規化** + **Hugging Face Inference Client (API)**。支援 JSON/CSV/TXT/**W3C Log** 執行**IP 關聯批量分析**。")
 
32
  # --- Streamlit Session State 初始化 (修正強化,確保所有變數都有初始值) ---
33
  if 'execute_batch_analysis' not in st.session_state:
34
  st.session_state.execute_batch_analysis = False
@@ -42,6 +47,7 @@ if 'vector_store' not in st.session_state:
42
  st.session_state.vector_store = None
43
  if 'json_data_for_batch' not in st.session_state:
44
  st.session_state.json_data_for_batch = None # 保持 None,因為可能檔案沒上傳
 
45
  # --- 定義模型列表 ---
46
  MODEL_OPTIONS = {
47
  "OpenAI GPT-OSS 20B (Hugging Face)": "openai/gpt-oss-20b",
@@ -49,8 +55,11 @@ MODEL_OPTIONS = {
49
  "Meta Llama 3.1 8B Instruct (Hugging Face)": "meta-llama/Llama-3.1-8B-Instruct",
50
  "Meta Llama 3.3 70B Instruct (Hugging Face)": "meta-llama/Llama-3.3-70B-Instruct",
51
  "fdtn-ai Foundation-Sec 8B Instruct (Hugging Face)": "fdtn-ai/Foundation-Sec-8B-Instruct",
52
- "Gemma 3 27B Instruct (Hugging Face)": "google/gemma-3-27b-it"}
 
 
53
  WINDOW_SIZE = 20 # 關聯 Log 的最大數量 (包含當前 Log)
 
54
  # === W3C Log 專屬解析器 (新增) ===
55
  def parse_w3c_log(log_content: str) -> List[Dict[str, Any]]:
56
  """
@@ -63,44 +72,46 @@ def parse_w3c_log(log_content: str) -> List[Dict[str, Any]]:
63
  lines = log_content.splitlines()
64
  field_names = None
65
  data_lines = []
66
-
67
  for line in lines:
68
  line = line.strip()
69
  if not line:
70
  continue
71
-
72
  if line.startswith("#Fields:"):
73
  # 找到欄位定義,例如 "#Fields: date time s-ip cs-method ..."
74
  field_names = line.split()[1:] # 跳過 "#Fields:" 本身
75
  elif not line.startswith("#"):
76
  # 這是實際的資料行
77
  data_lines.append(line)
78
-
79
  if not field_names:
80
  # 如果沒有找到 #Fields,則退回到原始 Log 條目模式
81
  # st.warning("未檢測到 W3C Log 的 #Fields: 標頭,退回原始 Log 條目模式。")
82
  return [{"raw_log_entry": line} for line in lines if line.strip() and not line.startswith("#")]
 
83
  json_data = []
84
-
85
  # 定義需要轉換為數字的欄位名稱 (可根據您的需求擴充,使用底線版本)
86
  numeric_fields = ['sc_status', 'time_taken', 'bytes', 'resp_len', 'req_size']
 
87
  for data_line in data_lines:
88
  # W3C Log 預設使用空格分隔。這裡使用 split()
89
  values = data_line.split(' ')
90
-
91
  # 簡易的欄位數量檢查
92
  if len(values) != len(field_names):
93
  # 如果欄位數量不匹配,將該行視為原始 Log 條目
94
  json_data.append({"raw_log_entry": data_line})
95
  continue
96
-
97
  record = {}
98
  for key, value in zip(field_names, values):
99
  # 將 W3C 欄位名稱中的 '-' 替換成 Python 友好的 '_'
100
  key = key.strip().replace('-', '_')
101
-
102
  value = value.strip() if value else ""
103
-
104
  # 處理數字轉換
105
  if key in numeric_fields:
106
  try:
@@ -112,11 +123,12 @@ def parse_w3c_log(log_content: str) -> List[Dict[str, Any]]:
112
  record[key] = value
113
  else:
114
  record[key] = value
115
-
116
  if record:
117
  json_data.append(record)
118
-
119
  return json_data
 
120
  # === 核心檔案轉換函式 (CSV/TXT -> JSON List) (保留並微調) ===
121
  def convert_csv_txt_to_json_list(file_content: bytes, file_type: str) -> List[Dict[str, Any]]:
122
  """
@@ -125,28 +137,29 @@ def convert_csv_txt_to_json_list(file_content: bytes, file_type: str) -> List[Di
125
  log_content = file_content.decode("utf-8").strip()
126
  if not log_content:
127
  return []
128
-
129
- string_io = io.StringIO(log_content)
130
 
 
 
131
  # 嘗試使用 csv.DictReader 自動將第一行視為 Key
132
  try:
133
  reader = csv.DictReader(string_io)
134
  except Exception:
135
  # 如果失敗,退回每行一個原始 Log 條目
136
  return [{"raw_log_entry": line.strip()} for line in log_content.splitlines() if line.strip()]
 
137
  json_data = []
138
  if reader and reader.fieldnames:
139
  # 使用者可能使用的數值欄位名稱
140
  numeric_fields = ['sc-status', 'time-taken', 'bytes', 'resp-len', 'req-size', 'status_code', 'size', 'duration']
141
-
142
  for row in reader:
143
  record = {}
144
  for key, value in row.items():
145
  if key is None: continue
146
-
147
  key = key.strip()
148
  value = value.strip() if value else ""
149
-
150
  # 處理數字轉換
151
  if key in numeric_fields:
152
  try:
@@ -158,26 +171,29 @@ def convert_csv_txt_to_json_list(file_content: bytes, file_type: str) -> List[Di
158
  record[key] = value
159
  else:
160
  record[key] = value
161
-
162
- if record:
163
- json_data.append(record)
164
- # 再次檢查是否為空,如果是空,可能不是標準 CSV/JSON
 
165
  if not json_data:
166
  string_io.seek(0)
167
  lines = string_io.readlines()
168
  return [{"raw_log_entry": line.strip()} for line in lines if line.strip()]
 
169
  return json_data
 
170
  # === 檔案類型分發器 (已修改) ===
171
  def convert_uploaded_file_to_json_list(uploaded_file) -> List[Dict[str, Any]]:
172
  """根據檔案類型,將上傳的檔案內容轉換為 Log JSON 列表。"""
173
  file_bytes = uploaded_file.getvalue()
174
  file_name_lower = uploaded_file.name.lower()
175
-
176
  # --- Case 1: JSON ---
177
  if file_name_lower.endswith('.json'):
178
  stringio = io.StringIO(file_bytes.decode("utf-8"))
179
  parsed_data = json.load(stringio)
180
-
181
  if isinstance(parsed_data, dict):
182
  # 處理包裹在 'alerts' 或 'logs' 鍵中的列表
183
  if 'alerts' in parsed_data and isinstance(parsed_data['alerts'], list):
@@ -190,27 +206,28 @@ def convert_uploaded_file_to_json_list(uploaded_file) -> List[Dict[str, Any]]:
190
  return parsed_data # 列表直接返回
191
  else:
192
  raise ValueError("JSON 檔案格式不支援 (非 List 或 Dict)。")
193
-
194
  # --- Case 2, 3, & 4: CSV/TXT/LOG ---
195
  elif file_name_lower.endswith(('.csv', '.txt', '.log')):
196
  file_type = 'csv' if file_name_lower.endswith('.csv') else ('log' if file_name_lower.endswith('.log') else 'txt')
197
-
198
  if file_type == 'log':
199
  # 針對 .log 檔案,嘗試使用 W3C 解析器
200
  log_content = file_bytes.decode("utf-8").strip()
201
  if not log_content: return []
202
  return parse_w3c_log(log_content)
203
-
204
  else:
205
  # CSV 和 TXT 保持使用原來的 csv.DictReader 邏輯
206
  return convert_csv_txt_to_json_list(file_bytes, file_type)
207
-
208
  else:
209
  raise ValueError("不支援的檔案類型。")
 
210
  # --- 側邊欄設定 (已更新 'type' 參數) ---
211
  with st.sidebar:
212
  st.header("⚙️ 設定")
213
-
214
  # --- 新增模型選單 ---
215
  selected_model_name = st.selectbox(
216
  "選擇 LLM 模型",
@@ -218,14 +235,15 @@ with st.sidebar:
218
  index=0 # 預設選擇第一個
219
  )
220
  MODEL_ID = MODEL_OPTIONS[selected_model_name] # 更新 MODEL_ID
221
-
222
  if not os.environ.get("HF_TOKEN"):
223
  st.error("環境變數 **HF_TOKEN** 未設定。請設定後重新啟動應用程式。")
224
  st.info(f"LLM 模型:**{MODEL_ID}** (Hugging Face Inference API)")
225
  st.warning("⚠️ **注意**: 該模型使用 Inference API 呼叫,請確保您的 HF Token 具有存取權限。")
 
226
  st.divider()
227
  st.subheader("📂 檔案上傳")
228
-
229
  # === 1. 批量分析檔案 (支援多種格式) ===
230
  batch_uploaded_file = st.file_uploader(
231
  "1️⃣ 上傳 **Log/Alert 檔案** (用於批量分析)",
@@ -233,7 +251,7 @@ with st.sidebar:
233
  key="batch_uploader",
234
  help="支援 JSON (Array), CSV (含標題), TXT/LOG (視為 W3C 或一般 Log)"
235
  )
236
-
237
  # === 2. RAG 知識庫檔案 ===
238
  rag_uploaded_file = st.file_uploader(
239
  "2️⃣ 上傳 **RAG 參考知識庫** (Logs/PDF/Code 等)",
@@ -241,7 +259,7 @@ with st.sidebar:
241
  key="rag_uploader"
242
  )
243
  st.divider()
244
-
245
  st.subheader("💡 批量分析指令")
246
  analysis_prompt = st.text_area(
247
  "針對每個 Log/Alert 執行的指令",
@@ -249,7 +267,7 @@ with st.sidebar:
249
  height=200
250
  )
251
  st.markdown("此指令將對檔案中的**每一個 Log 條目**執行一次獨立分析 (使用 **IP 關聯視窗**)。")
252
-
253
  if batch_uploaded_file:
254
  if st.button("🚀 執行批量分析"):
255
  if not os.environ.get("HF_TOKEN"):
@@ -262,18 +280,18 @@ with st.sidebar:
262
  st.error("請先等待 Log 檔案解析完成。")
263
  else:
264
  st.info("請上傳 Log 檔案以啟用批量分析按鈕。")
265
-
266
  st.divider()
267
  st.subheader("🔍 RAG 檢索設定")
268
  similarity_threshold = st.slider("📐 Cosine Similarity 門檻", 0.0, 1.0, 0.4, 0.01)
269
-
270
  st.divider()
271
  st.subheader("模型參數")
272
  system_prompt = st.text_area("System Prompt", value="You are a Senior Security Analyst, named Ernest. You provide expert, authoritative, and concise advice on Information Security. Your analysis must be based strictly on the provided context.", height=100)
273
  max_output_tokens = st.slider("Max Output Tokens", 128, 4096, 2048, 128)
274
  temperature = st.slider("Temperature", 0.0, 1.0, 0.1, 0.1)
275
  top_p = st.slider("Top P", 0.1, 1.0, 0.95, 0.05)
276
-
277
  st.divider()
278
  if st.button("🗑️ 清除所有紀錄"):
279
  # 僅清除動態狀態,保留 HF_TOKEN
@@ -281,6 +299,7 @@ with st.sidebar:
281
  if key not in ['HF_TOKEN']:
282
  del st.session_state[key]
283
  st.rerun()
 
284
  # --- 初始化 Hugging Face LLM Client (已更新,MODEL_ID 作為參數) ---
285
  # 確保 load_inference_client 接受 model_id 作為參數,以利用 Streamlit 的快取機制。
286
  @st.cache_resource
@@ -293,23 +312,28 @@ def load_inference_client(model_id):
293
  except Exception as e:
294
  st.error(f"Hugging Face Inference Client 載入失敗: {e}")
295
  return None
 
296
  inference_client = None
297
  if os.environ.get("HF_TOKEN"):
298
  with st.spinner(f"正在連線到 Inference Client: {MODEL_ID}..."):
299
  # 傳遞 MODEL_ID
300
- inference_client = load_inference_client(MODEL_ID)
 
301
  if inference_client is None and os.environ.get("HF_TOKEN"):
302
  st.warning(f"Hugging Face Inference Client **{MODEL_ID}** 無法連線。")
303
  elif not os.environ.get("HF_TOKEN"):
304
  st.error("請在環境變數中設定 HF_TOKEN。")
 
305
  # === Embedding 模型 (保持不變) ===
306
  @st.cache_resource
307
  def load_embedding_model():
308
  model_kwargs = {'device': 'cpu', 'trust_remote_code': True}
309
  encode_kwargs = {'normalize_embeddings': False}
310
  return HuggingFaceEmbeddings(model_name="BAAI/bge-large-zh-v1.5", model_kwargs=model_kwargs, encode_kwargs=encode_kwargs)
 
311
  with st.spinner("正在載入 Embedding 模型..."):
312
  embedding_model = load_embedding_model()
 
313
  # === 建立向量庫 / Search 函數 (保持不變) ===
314
  def process_file_to_faiss(uploaded_file):
315
  text_content = ""
@@ -323,32 +347,33 @@ def process_file_to_faiss(uploaded_file):
323
  else:
324
  stringio = io.StringIO(uploaded_file.getvalue().decode("utf-8"))
325
  text_content = stringio.read()
326
-
327
  if not text_content.strip(): return None, "File is empty"
328
-
329
  # 這裡將文件內容按行分割為 Document,每行一個 Document
330
  events = [line for line in text_content.splitlines() if line.strip()]
331
  docs = [Document(page_content=e) for e in events]
332
  if not docs: return None, "No documents created"
333
-
334
  # 進行 Embedding 和 FAISS 初始化 (IndexFlatIP + L2 normalization)
335
  embeddings = embedding_model.embed_documents([d.page_content for d in docs])
336
  embeddings_np = np.array(embeddings).astype("float32")
337
  faiss.normalize_L2(embeddings_np)
338
-
339
  dimension = embeddings_np.shape[1]
340
  index = faiss.IndexFlatIP(dimension) # 使用內積 (Inner Product)
341
  index.add(embeddings_np)
342
-
343
  doc_ids = [str(uuid.uuid4()) for _ in range(len(docs))]
344
  docstore = InMemoryDocstore({_id: doc for _id, doc in zip(doc_ids, docs)})
345
  index_to_docstore_id = {i: _id for i, _id in enumerate(doc_ids)}
346
-
347
  # 使用 Cosine 距離策略,配合 IndexFlatIP 和 L2 normalization 達到 Cosine Similarity
348
  vector_store = FAISS(embedding_function=embedding_model, index=index, docstore=docstore, index_to_docstore_id=index_to_docstore_id, distance_strategy=DistanceStrategy.COSINE)
349
  return vector_store, f"{len(docs)} chunks created."
350
  except Exception as e:
351
  return None, f"Error: {str(e)}"
 
352
  def faiss_cosine_search_all(vector_store, query, threshold):
353
  q_emb = embedding_model.embed_query(query)
354
  q_emb = np.array([q_emb]).astype("float32")
@@ -356,7 +381,7 @@ def faiss_cosine_search_all(vector_store, query, threshold):
356
  index = vector_store.index
357
  D, I = index.search(q_emb, k=index.ntotal)
358
  selected = []
359
-
360
  # Cosine Similarity = D (IndexFlatIP + L2 normalization)
361
  for score, idx in zip(D[0], I[0]):
362
  if idx == -1: continue
@@ -365,14 +390,15 @@ def faiss_cosine_search_all(vector_store, query, threshold):
365
  doc_id = vector_store.index_to_docstore_id[idx]
366
  doc = vector_store.docstore.search(doc_id)
367
  selected.append((doc, score))
368
-
369
  selected.sort(key=lambda x: x[1], reverse=True)
370
  return selected
 
371
  # === Hugging Face 生成單一 Log 分析回答 (保持不變) ===
372
  def generate_rag_response_hf_for_log(client, model_id, log_sequence_text, user_prompt, sys_prompt, vector_store, threshold, max_output_tokens, temperature, top_p):
373
  if client is None: return "ERROR: Client Error", ""
374
  context_text = ""
375
-
376
  # RAG 檢索邏輯
377
  if vector_store:
378
  selected = faiss_cosine_search_all(vector_store, log_sequence_text, threshold)
@@ -380,15 +406,16 @@ def generate_rag_response_hf_for_log(client, model_id, log_sequence_text, user_p
380
  # 只取前 5 個最相關的片段
381
  retrieved_contents = [f"--- Reference Chunk (sim={score:.3f}) ---\n{doc.page_content}" for i, (doc, score) in enumerate(selected[:5])]
382
  context_text = "\n".join(retrieved_contents)
383
-
384
  rag_instruction = f"""=== RETRIEVED REFERENCE CONTEXT (Cosine ≥ {threshold}) ==={context_text if context_text else 'No relevant reference context found.'}=== END REFERENCE CONTEXT ===ANALYSIS INSTRUCTION: {user_prompt}Based on the provided LOG SEQUENCE and REFERENCE CONTEXT, you must analyze the **entire sequence** to detect any continuous attack chains or evolving threats."""
 
385
  log_content_section = f"""=== CURRENT LOG SEQUENCE TO ANALYZE (Window Size: Max {WINDOW_SIZE} logs associated by IP) ==={log_sequence_text}=== END LOG SEQUENCE ==="""
386
-
387
  messages = [
388
  {"role": "system", "content": sys_prompt},
389
  {"role": "user", "content": f"{rag_instruction}\n\n{log_content_section}"}
390
  ]
391
-
392
  try:
393
  # 使用 chat_completion 進行模型呼叫
394
  response_stream = client.chat_completion(
@@ -401,8 +428,9 @@ def generate_rag_response_hf_for_log(client, model_id, log_sequence_text, user_p
401
  if response_stream and response_stream.choices:
402
  return response_stream.choices[0].message.content.strip(), context_text
403
  else: return "Format Error: Model returned empty response or invalid format.", context_text
404
- except Exception as e:
405
- return f"Model Error: {str(e)}", context_text
 
406
  # =======================================================================
407
  # === 檔案處理區塊 (RAG 檔案) - 保持不變 ===
408
  if rag_uploaded_file:
@@ -411,7 +439,7 @@ if rag_uploaded_file:
411
  # 清除舊的 vector store 以節省內存
412
  if 'vector_store' in st.session_state:
413
  del st.session_state.vector_store
414
-
415
  with st.spinner(f"正在建立 RAG 參考知識庫 ({rag_uploaded_file.name})..."):
416
  vs, msg = process_file_to_faiss(rag_uploaded_file)
417
  if vs:
@@ -425,10 +453,11 @@ elif 'vector_store' in st.session_state:
425
  del st.session_state.vector_store
426
  del st.session_state.rag_current_file_key
427
  st.info("RAG 檔案已移除,已清除相關知識庫。")
 
428
  # === 檔案處理區塊 (批量分析檔案 - **已更新** ) ===
429
  if batch_uploaded_file:
430
  batch_file_key = f"batch_{batch_uploaded_file.name}_{batch_uploaded_file.size}"
431
-
432
  if st.session_state.batch_current_file_key != batch_file_key or 'json_data_for_batch' not in st.session_state:
433
  try:
434
  # 清除舊的數據
@@ -438,15 +467,15 @@ if batch_uploaded_file:
438
  del st.session_state.batch_results
439
  # 使用新的統一解析函式
440
  parsed_data = convert_uploaded_file_to_json_list(batch_uploaded_file)
441
-
442
  if not parsed_data:
443
  raise ValueError(f"{batch_uploaded_file.name} 檔案載入失敗或內容為空。")
444
-
445
  # 儲存處理後的數據
446
  st.session_state.json_data_for_batch = parsed_data
447
  st.session_state.batch_current_file_key = batch_file_key
448
  st.toast(f"檔案已解析並轉換為 {len(parsed_data)} 個 Log 條目。", icon="✅")
449
-
450
  except Exception as e:
451
  st.error(f"檔案解析錯誤: {e}")
452
  if 'json_data_for_batch' in st.session_state:
@@ -460,87 +489,88 @@ elif 'json_data_for_batch' in st.session_state:
460
  if "batch_results" in st.session_state:
461
  del st.session_state.batch_results
462
  st.info("批量分析檔案已移除,已清除相關數據和結果。")
 
463
  # === 執行批量分析邏輯 (已修改為 IP 關聯視窗) ===
464
  if st.session_state.execute_batch_analysis and 'json_data_for_batch' in st.session_state and st.session_state.json_data_for_batch is not None:
465
  st.session_state.execute_batch_analysis = False
466
  start_time = time.time()
467
-
468
  # 這裡必須確保 st.session_state.batch_results 是 List,而不是 None
469
  if 'batch_results' not in st.session_state or st.session_state.batch_results is None:
470
  st.session_state.batch_results = []
471
-
472
- st.session_state.batch_results = []
473
 
 
 
474
  if inference_client is None:
475
  st.error("Client 未連線,無法執行。")
476
  else:
477
  logs_list = st.session_state.json_data_for_batch
478
-
479
  if logs_list:
480
  vs = st.session_state.get("vector_store", None)
481
-
482
  # 將 Log 條目轉換為 JSON 字串,用於 LLM 輸入
483
  formatted_logs = [json.dumps(log, indent=2, ensure_ascii=False) for log in logs_list]
484
-
485
  analysis_sequences = []
486
-
487
  # --- 核心修改:基於 IP 關聯的 Log Sequence 建構 ---
488
  for i in range(len(formatted_logs)):
489
  current_log_entry = logs_list[i]
490
  current_log_str = formatted_logs[i]
491
-
492
  # 嘗試從當前 Log 條目中提取 IP 地址 (優先 W3C 格式,然後是一般日誌格式)
493
  # 使用者可以根據自己的日誌格式調整這裡的 Key
494
  target_ip = current_log_entry.get('c_ip') or current_log_entry.get('c-ip') or current_log_entry.get('remote_addr') or current_log_entry.get('source_ip')
495
-
496
  sequence_text = []
497
  correlated_logs = []
498
-
499
  if target_ip and target_ip != "-": # 假設 '-' 是 W3C 中的空值
500
-
501
  # 篩選過去的 Log,最多 WINDOW_SIZE - 1 個,且 IP 必須匹配
502
  # 從 i-1 倒序檢查到 0
503
  for j in range(i - 1, -1, -1):
504
  prior_log_entry = logs_list[j]
505
  prior_ip = prior_log_entry.get('c_ip') or prior_log_entry.get('c-ip') or prior_log_entry.get('remote_addr') or prior_log_entry.get('source_ip')
506
-
507
  # 檢查 IP 是否匹配
508
  if prior_ip == target_ip:
509
  # 插入到最前面,保持時間順序
510
  correlated_logs.insert(0, formatted_logs[j])
511
-
512
- # 限制累積的 Log 數量(不包含當前 Log)
513
- if len(correlated_logs) >= WINDOW_SIZE - 1:
514
- break
515
-
516
  # 1. 加入相關聯的 Log (時間較早的)
517
  for j, log_str in enumerate(correlated_logs):
518
  # log_idx 是這些 Log 在 logs_list 中的原始索引 (不完全準確,但提供參考)
519
  sequence_text.append(f"--- Correlated Log Index (IP:{target_ip}) ---\n{log_str}")
520
-
521
  else:
522
  # 如果沒有找到 IP���只分析當前 Log (確保 sequence_text 不是空的)
523
  st.warning(f"Log #{i+1} 找不到 IP 欄位 ({target_ip}),僅分析當前 Log 條目。")
524
-
525
  # 2. 加入當前的目標 Log
526
  sequence_text.append(f"--- TARGET LOG TO ANALYZE (Index {i+1}) ---\n{current_log_str}")
527
-
528
  analysis_sequences.append({
529
  "sequence_text": "\n\n".join(sequence_text),
530
  "target_log_id": i + 1,
531
  "original_log_entry": logs_list[i]
532
  })
533
-
534
  # --- LLM 執行迴圈 ---
535
  total_sequences = len(analysis_sequences)
536
  st.header(f"⚡ 批量分析執行中 (IP 關聯視窗 $N={WINDOW_SIZE}$)...")
537
  progress_bar = st.progress(0, text=f"準備處理 {total_sequences} 個序列...")
538
  results_container = st.container()
539
-
540
  for i, seq_data in enumerate(analysis_sequences):
541
  log_id = seq_data["target_log_id"]
542
  progress_bar.progress((i + 1) / total_sequences, text=f"Processing {i + 1}/{total_sequences} (Log #{log_id})...")
543
-
544
  try:
545
  response, retrieved_ctx = generate_rag_response_hf_for_log(
546
  client=inference_client,
@@ -554,7 +584,7 @@ if st.session_state.execute_batch_analysis and 'json_data_for_batch' in st.sessi
554
  temperature=temperature,
555
  top_p=top_p
556
  )
557
-
558
  item = {
559
  "log_id": log_id,
560
  "log_content": seq_data["original_log_entry"],
@@ -562,111 +592,77 @@ if st.session_state.execute_batch_analysis and 'json_data_for_batch' in st.sessi
562
  "analysis_result": response,
563
  "context": retrieved_ctx
564
  }
565
-
566
  st.session_state.batch_results.append(item)
567
-
568
- # --- 核心修改:僅顯示 High 或 Medium Risk ---
569
- is_high = any(x in response.lower() for x in ['high-risk detected'])
570
- is_medium = any(x in response.lower() for x in ['medium-risk detected'])
571
-
572
- if is_high or is_medium: # 只有 High 或 Medium 才顯示在儀表板
573
- with results_container:
574
- st.subheader(f"Log/Alert #{item['log_id']} (IP Correlated Analysis)")
575
-
576
  with st.expander("序列內容 (JSON Format)"):
577
  st.code(item["sequence_analyzed"], language='json')
578
-
579
- # 呈現 LLM 分析結果
580
- if is_high:
581
  st.error(item['analysis_result'])
582
- elif is_medium: # 如果不是 High,再檢查是否為 Medium
583
- st.warning(item['analysis_result'])
584
-
585
- if item['context']:
586
- with st.expander("參考 RAG 片段"): st.code(item['context'])
587
- st.markdown("---")
588
- # --- 結束核心修改 ---
589
-
 
 
 
 
 
590
  except Exception as e:
591
  st.error(f"Error Log {log_id}: {e}")
592
-
593
  end_time = time.time()
594
  progress_bar.empty()
595
  st.success(f"完成!耗時 {end_time - start_time:.2f} 秒。")
596
  else:
597
  st.error("無法提取有效 Log,請檢查檔案格式。")
598
 
599
- # === 顯示結果 (歷史紀錄) - **已修改**僅顯示 High/Medium Risk,並更新 CSV 報告 ===
600
  if st.session_state.get("batch_results") and isinstance(st.session_state.batch_results, list) and st.session_state.batch_results and not st.session_state.execute_batch_analysis:
601
- st.header("⚡ 歷史分析結果 (僅顯示 High/Medium Risk)")
602
-
603
- high_medium_risk_data = []
604
  high_risk_items = []
605
- medium_risk_items = []
606
-
607
  for item in st.session_state.batch_results:
608
  # 檢查 analysis_result 中是否包含 'High-risk detected' (不區分大小寫)
609
  is_high_risk = 'high-risk detected!' in item['analysis_result'].lower()
610
- is_medium_risk = 'medium-risk detected!' in item['analysis_result'].lower() # 檢查 Medium Risk
611
-
612
  if is_high_risk:
613
  high_risk_items.append(item)
614
- risk_level = "HIGH_RISK"
615
- elif is_medium_risk:
616
- medium_risk_items.append(item)
617
- risk_level = "MEDIUM_RISK"
618
- else:
619
- continue # 跳過 Low Risk
620
 
621
- # --- 為 CSV 報告準備數據 (包含 High 和 Medium) ---
622
- log_content_str = json.dumps(item["log_content"], ensure_ascii=False)
623
- analysis_result_clean = item['analysis_result'].replace('\n', ' | ')
624
-
625
- high_medium_risk_data.append({
626
- "Log_ID": item['log_id'],
627
- "Risk_Level": risk_level,
628
- "Log_Content": log_content_str,
629
- "AI_Analysis_Result": analysis_result_clean
630
- })
631
-
632
- total_risky_items = len(high_risk_items) + len(medium_risk_items)
633
-
634
- # 顯示 High-Risk 報告的下載按鈕 (改為 CSV 邏輯)
635
- if total_risky_items > 0:
636
- st.success(f"✅ 檢測到 {len(high_risk_items)} 條高風險 Log/Alert 及 {len(medium_risk_items)} 條中風險 Log/Alert。")
637
 
638
- # --- 顯示所有 High/Medium Risk 項目 ---
639
- # 先顯示 High Risk
640
- for item in high_risk_items:
641
- st.subheader(f"Log/Alert #{item['log_id']} (HIGH-RISK)")
642
- st.error(item['analysis_result'])
643
- with st.expander("序列內容 (JSON Format)"):
644
- st.code(item["sequence_analyzed"], language='json')
645
- if item['context']:
646
- with st.expander("參考 RAG 片段"): st.code(item['context'])
647
- st.markdown("---")
648
-
649
- # 再顯示 Medium Risk
650
- for item in medium_risk_items:
651
- st.subheader(f"Log/Alert #{item['log_id']} (MEDIUM-RISK)")
652
- st.warning(item['analysis_result'])
653
- with st.expander("序列內容 (JSON Format)"):
654
- st.code(item["sequence_analyzed"], language='json')
655
- if item['context']:
656
- with st.expander("參考 RAG 片段"): st.code(item['context'])
657
- st.markdown("---")
658
- # --- 結束顯示 ---
659
-
660
-
661
- # --- 構建 CSV 內容 --- (包含 High 和 Medium)
662
  csv_output = io.StringIO()
663
  csv_output.write("Log_ID,Risk_Level,Log_Content,AI_Analysis_Result\n")
664
-
665
  def escape_csv(value):
666
  # 替換內容中的所有雙引號為兩個雙引號,然後用雙引號包圍
667
  return f'"{str(value).replace('"', '""')}"'
668
-
669
- for row in high_medium_risk_data:
670
  line = ",".join([
671
  str(row["Log_ID"]),
672
  row["Risk_Level"],
@@ -674,15 +670,16 @@ if st.session_state.get("batch_results") and isinstance(st.session_state.batch_r
674
  escape_csv(row["AI_Analysis_Result"])
675
  ]) + "\n"
676
  csv_output.write(line)
677
-
678
  csv_content = csv_output.getvalue()
679
-
680
- # 顯示 CSV 報告的下載按鈕 (名稱已更新)
681
  st.download_button(
682
- "📥 下載 **高/中風險** 分析報告 (.csv)",
683
  csv_content,
684
- "high_medium_risk_report.csv",
685
  "text/csv"
686
  )
687
  else:
688
- st.info("👍 未檢測到任何標註為 High-risk detected 或 Medium-risk detected 的 Log/Alert。")
 
 
9
  import time
10
  import sys
11
  from typing import List, Dict, Any
12
+
13
  # === HuggingFace 模型相關套件 (替換為 InferenceClient) ===
14
  try:
15
  from huggingface_hub import InferenceClient
16
  except ImportError:
17
  st.error("請檢查是否安裝了所有 Hugging Face 相關依賴:pip install huggingface-hub")
18
+
19
  # === LangChain/RAG 相關套件 (保持不變) ===
20
  from langchain_community.embeddings import HuggingFaceEmbeddings
21
  from langchain_core.documents import Document
22
  from langchain_community.vectorstores import FAISS
23
  from langchain_community.vectorstores.utils import DistanceStrategy
24
  from langchain_community.docstore.in_memory import InMemoryDocstore
25
+
26
+ # 嘗試匯入 pypdftry:
27
  try:
28
  import pypdf
29
  except ImportError:
30
  pypdf = None
31
+
32
  # --- 頁面設定 ---
33
  st.set_page_config(page_title="Cybersecurity AI Assistant (Hugging Face RAG & IP Correlated Analysis)", page_icon="🛡️", layout="wide")
34
  st.title("🛡️ LLM with FAISS RAG & IP Correlated Analysis (Inference Client)")
35
  st.markdown("已啟用:**IndexFlatIP** + **L2 正規化** + **Hugging Face Inference Client (API)**。支援 JSON/CSV/TXT/**W3C Log** 執行**IP 關聯批量分析**。")
36
+
37
  # --- Streamlit Session State 初始化 (修正強化,確保所有變數都有初始值) ---
38
  if 'execute_batch_analysis' not in st.session_state:
39
  st.session_state.execute_batch_analysis = False
 
47
  st.session_state.vector_store = None
48
  if 'json_data_for_batch' not in st.session_state:
49
  st.session_state.json_data_for_batch = None # 保持 None,因為可能檔案沒上傳
50
+
51
  # --- 定義模型列表 ---
52
  MODEL_OPTIONS = {
53
  "OpenAI GPT-OSS 20B (Hugging Face)": "openai/gpt-oss-20b",
 
55
  "Meta Llama 3.1 8B Instruct (Hugging Face)": "meta-llama/Llama-3.1-8B-Instruct",
56
  "Meta Llama 3.3 70B Instruct (Hugging Face)": "meta-llama/Llama-3.3-70B-Instruct",
57
  "fdtn-ai Foundation-Sec 8B Instruct (Hugging Face)": "fdtn-ai/Foundation-Sec-8B-Instruct",
58
+ "Gemma 3 27B Instruct (Hugging Face)": "google/gemma-3-27b-it"
59
+ }
60
+
61
  WINDOW_SIZE = 20 # 關聯 Log 的最大數量 (包含當前 Log)
62
+
63
  # === W3C Log 專屬解析器 (新增) ===
64
  def parse_w3c_log(log_content: str) -> List[Dict[str, Any]]:
65
  """
 
72
  lines = log_content.splitlines()
73
  field_names = None
74
  data_lines = []
75
+
76
  for line in lines:
77
  line = line.strip()
78
  if not line:
79
  continue
80
+
81
  if line.startswith("#Fields:"):
82
  # 找到欄位定義,例如 "#Fields: date time s-ip cs-method ..."
83
  field_names = line.split()[1:] # 跳過 "#Fields:" 本身
84
  elif not line.startswith("#"):
85
  # 這是實際的資料行
86
  data_lines.append(line)
87
+
88
  if not field_names:
89
  # 如果沒有找到 #Fields,則退回到原始 Log 條目模式
90
  # st.warning("未檢測到 W3C Log 的 #Fields: 標頭,退回原始 Log 條目模式。")
91
  return [{"raw_log_entry": line} for line in lines if line.strip() and not line.startswith("#")]
92
+
93
  json_data = []
94
+
95
  # 定義需要轉換為數字的欄位名稱 (可根據您的需求擴充,使用底線版本)
96
  numeric_fields = ['sc_status', 'time_taken', 'bytes', 'resp_len', 'req_size']
97
+
98
  for data_line in data_lines:
99
  # W3C Log 預設使用空格分隔。這裡使用 split()
100
  values = data_line.split(' ')
101
+
102
  # 簡易的欄位數量檢查
103
  if len(values) != len(field_names):
104
  # 如果欄位數量不匹配,將該行視為原始 Log 條目
105
  json_data.append({"raw_log_entry": data_line})
106
  continue
107
+
108
  record = {}
109
  for key, value in zip(field_names, values):
110
  # 將 W3C 欄位名稱中的 '-' 替換成 Python 友好的 '_'
111
  key = key.strip().replace('-', '_')
112
+
113
  value = value.strip() if value else ""
114
+
115
  # 處理數字轉換
116
  if key in numeric_fields:
117
  try:
 
123
  record[key] = value
124
  else:
125
  record[key] = value
126
+
127
  if record:
128
  json_data.append(record)
129
+
130
  return json_data
131
+
132
  # === 核心檔案轉換函式 (CSV/TXT -> JSON List) (保留並微調) ===
133
  def convert_csv_txt_to_json_list(file_content: bytes, file_type: str) -> List[Dict[str, Any]]:
134
  """
 
137
  log_content = file_content.decode("utf-8").strip()
138
  if not log_content:
139
  return []
 
 
140
 
141
+ string_io = io.StringIO(log_content)
142
+
143
  # 嘗試使用 csv.DictReader 自動將第一行視為 Key
144
  try:
145
  reader = csv.DictReader(string_io)
146
  except Exception:
147
  # 如果失敗,退回每行一個原始 Log 條目
148
  return [{"raw_log_entry": line.strip()} for line in log_content.splitlines() if line.strip()]
149
+
150
  json_data = []
151
  if reader and reader.fieldnames:
152
  # 使用者可能使用的數值欄位名稱
153
  numeric_fields = ['sc-status', 'time-taken', 'bytes', 'resp-len', 'req-size', 'status_code', 'size', 'duration']
154
+
155
  for row in reader:
156
  record = {}
157
  for key, value in row.items():
158
  if key is None: continue
159
+
160
  key = key.strip()
161
  value = value.strip() if value else ""
162
+
163
  # 處理數字轉換
164
  if key in numeric_fields:
165
  try:
 
171
  record[key] = value
172
  else:
173
  record[key] = value
174
+
175
+ if record:
176
+ json_data.append(record)
177
+
178
+ # 再次檢查是否為空,如果是空,可能不是標準 CSV/JSON
179
  if not json_data:
180
  string_io.seek(0)
181
  lines = string_io.readlines()
182
  return [{"raw_log_entry": line.strip()} for line in lines if line.strip()]
183
+
184
  return json_data
185
+
186
  # === 檔案類型分發器 (已修改) ===
187
  def convert_uploaded_file_to_json_list(uploaded_file) -> List[Dict[str, Any]]:
188
  """根據檔案類型,將上傳的檔案內容轉換為 Log JSON 列表。"""
189
  file_bytes = uploaded_file.getvalue()
190
  file_name_lower = uploaded_file.name.lower()
191
+
192
  # --- Case 1: JSON ---
193
  if file_name_lower.endswith('.json'):
194
  stringio = io.StringIO(file_bytes.decode("utf-8"))
195
  parsed_data = json.load(stringio)
196
+
197
  if isinstance(parsed_data, dict):
198
  # 處理包裹在 'alerts' 或 'logs' 鍵中的列表
199
  if 'alerts' in parsed_data and isinstance(parsed_data['alerts'], list):
 
206
  return parsed_data # 列表直接返回
207
  else:
208
  raise ValueError("JSON 檔案格式不支援 (非 List 或 Dict)。")
209
+
210
  # --- Case 2, 3, & 4: CSV/TXT/LOG ---
211
  elif file_name_lower.endswith(('.csv', '.txt', '.log')):
212
  file_type = 'csv' if file_name_lower.endswith('.csv') else ('log' if file_name_lower.endswith('.log') else 'txt')
213
+
214
  if file_type == 'log':
215
  # 針對 .log 檔案,嘗試使用 W3C 解析器
216
  log_content = file_bytes.decode("utf-8").strip()
217
  if not log_content: return []
218
  return parse_w3c_log(log_content)
219
+
220
  else:
221
  # CSV 和 TXT 保持使用原來的 csv.DictReader 邏輯
222
  return convert_csv_txt_to_json_list(file_bytes, file_type)
223
+
224
  else:
225
  raise ValueError("不支援的檔案類型。")
226
+
227
  # --- 側邊欄設定 (已更新 'type' 參數) ---
228
  with st.sidebar:
229
  st.header("⚙️ 設定")
230
+
231
  # --- 新增模型選單 ---
232
  selected_model_name = st.selectbox(
233
  "選擇 LLM 模型",
 
235
  index=0 # 預設選擇第一個
236
  )
237
  MODEL_ID = MODEL_OPTIONS[selected_model_name] # 更新 MODEL_ID
238
+
239
  if not os.environ.get("HF_TOKEN"):
240
  st.error("環境變數 **HF_TOKEN** 未設定。請設定後重新啟動應用程式。")
241
  st.info(f"LLM 模型:**{MODEL_ID}** (Hugging Face Inference API)")
242
  st.warning("⚠️ **注意**: 該模型使用 Inference API 呼叫,請確保您的 HF Token 具有存取權限。")
243
+
244
  st.divider()
245
  st.subheader("📂 檔案上傳")
246
+
247
  # === 1. 批量分析檔案 (支援多種格式) ===
248
  batch_uploaded_file = st.file_uploader(
249
  "1️⃣ 上傳 **Log/Alert 檔案** (用於批量分析)",
 
251
  key="batch_uploader",
252
  help="支援 JSON (Array), CSV (含標題), TXT/LOG (視為 W3C 或一般 Log)"
253
  )
254
+
255
  # === 2. RAG 知識庫檔案 ===
256
  rag_uploaded_file = st.file_uploader(
257
  "2️⃣ 上傳 **RAG 參考知識庫** (Logs/PDF/Code 等)",
 
259
  key="rag_uploader"
260
  )
261
  st.divider()
262
+
263
  st.subheader("💡 批量分析指令")
264
  analysis_prompt = st.text_area(
265
  "針對每個 Log/Alert 執行的指令",
 
267
  height=200
268
  )
269
  st.markdown("此指令將對檔案中的**每一個 Log 條目**執行一次獨立分析 (使用 **IP 關聯視窗**)。")
270
+
271
  if batch_uploaded_file:
272
  if st.button("🚀 執行批量分析"):
273
  if not os.environ.get("HF_TOKEN"):
 
280
  st.error("請先等待 Log 檔案解析完成。")
281
  else:
282
  st.info("請上傳 Log 檔案以啟用批量分析按鈕。")
283
+
284
  st.divider()
285
  st.subheader("🔍 RAG 檢索設定")
286
  similarity_threshold = st.slider("📐 Cosine Similarity 門檻", 0.0, 1.0, 0.4, 0.01)
287
+
288
  st.divider()
289
  st.subheader("模型參數")
290
  system_prompt = st.text_area("System Prompt", value="You are a Senior Security Analyst, named Ernest. You provide expert, authoritative, and concise advice on Information Security. Your analysis must be based strictly on the provided context.", height=100)
291
  max_output_tokens = st.slider("Max Output Tokens", 128, 4096, 2048, 128)
292
  temperature = st.slider("Temperature", 0.0, 1.0, 0.1, 0.1)
293
  top_p = st.slider("Top P", 0.1, 1.0, 0.95, 0.05)
294
+
295
  st.divider()
296
  if st.button("🗑️ 清除所有紀錄"):
297
  # 僅清除動態狀態,保留 HF_TOKEN
 
299
  if key not in ['HF_TOKEN']:
300
  del st.session_state[key]
301
  st.rerun()
302
+
303
  # --- 初始化 Hugging Face LLM Client (已更新,MODEL_ID 作為參數) ---
304
  # 確保 load_inference_client 接受 model_id 作為參數,以利用 Streamlit 的快取機制。
305
  @st.cache_resource
 
312
  except Exception as e:
313
  st.error(f"Hugging Face Inference Client 載入失敗: {e}")
314
  return None
315
+
316
  inference_client = None
317
  if os.environ.get("HF_TOKEN"):
318
  with st.spinner(f"正在連線到 Inference Client: {MODEL_ID}..."):
319
  # 傳遞 MODEL_ID
320
+ inference_client = load_inference_client(MODEL_ID)
321
+
322
  if inference_client is None and os.environ.get("HF_TOKEN"):
323
  st.warning(f"Hugging Face Inference Client **{MODEL_ID}** 無法連線。")
324
  elif not os.environ.get("HF_TOKEN"):
325
  st.error("請在環境變數中設定 HF_TOKEN。")
326
+
327
  # === Embedding 模型 (保持不變) ===
328
  @st.cache_resource
329
  def load_embedding_model():
330
  model_kwargs = {'device': 'cpu', 'trust_remote_code': True}
331
  encode_kwargs = {'normalize_embeddings': False}
332
  return HuggingFaceEmbeddings(model_name="BAAI/bge-large-zh-v1.5", model_kwargs=model_kwargs, encode_kwargs=encode_kwargs)
333
+
334
  with st.spinner("正在載入 Embedding 模型..."):
335
  embedding_model = load_embedding_model()
336
+
337
  # === 建立向量庫 / Search 函數 (保持不變) ===
338
  def process_file_to_faiss(uploaded_file):
339
  text_content = ""
 
347
  else:
348
  stringio = io.StringIO(uploaded_file.getvalue().decode("utf-8"))
349
  text_content = stringio.read()
350
+
351
  if not text_content.strip(): return None, "File is empty"
352
+
353
  # 這裡將文件內容按行分割為 Document,每行一個 Document
354
  events = [line for line in text_content.splitlines() if line.strip()]
355
  docs = [Document(page_content=e) for e in events]
356
  if not docs: return None, "No documents created"
357
+
358
  # 進行 Embedding 和 FAISS 初始化 (IndexFlatIP + L2 normalization)
359
  embeddings = embedding_model.embed_documents([d.page_content for d in docs])
360
  embeddings_np = np.array(embeddings).astype("float32")
361
  faiss.normalize_L2(embeddings_np)
362
+
363
  dimension = embeddings_np.shape[1]
364
  index = faiss.IndexFlatIP(dimension) # 使用內積 (Inner Product)
365
  index.add(embeddings_np)
366
+
367
  doc_ids = [str(uuid.uuid4()) for _ in range(len(docs))]
368
  docstore = InMemoryDocstore({_id: doc for _id, doc in zip(doc_ids, docs)})
369
  index_to_docstore_id = {i: _id for i, _id in enumerate(doc_ids)}
370
+
371
  # 使用 Cosine 距離策略,配合 IndexFlatIP 和 L2 normalization 達到 Cosine Similarity
372
  vector_store = FAISS(embedding_function=embedding_model, index=index, docstore=docstore, index_to_docstore_id=index_to_docstore_id, distance_strategy=DistanceStrategy.COSINE)
373
  return vector_store, f"{len(docs)} chunks created."
374
  except Exception as e:
375
  return None, f"Error: {str(e)}"
376
+
377
  def faiss_cosine_search_all(vector_store, query, threshold):
378
  q_emb = embedding_model.embed_query(query)
379
  q_emb = np.array([q_emb]).astype("float32")
 
381
  index = vector_store.index
382
  D, I = index.search(q_emb, k=index.ntotal)
383
  selected = []
384
+
385
  # Cosine Similarity = D (IndexFlatIP + L2 normalization)
386
  for score, idx in zip(D[0], I[0]):
387
  if idx == -1: continue
 
390
  doc_id = vector_store.index_to_docstore_id[idx]
391
  doc = vector_store.docstore.search(doc_id)
392
  selected.append((doc, score))
393
+
394
  selected.sort(key=lambda x: x[1], reverse=True)
395
  return selected
396
+
397
  # === Hugging Face 生成單一 Log 分析回答 (保持不變) ===
398
  def generate_rag_response_hf_for_log(client, model_id, log_sequence_text, user_prompt, sys_prompt, vector_store, threshold, max_output_tokens, temperature, top_p):
399
  if client is None: return "ERROR: Client Error", ""
400
  context_text = ""
401
+
402
  # RAG 檢索邏輯
403
  if vector_store:
404
  selected = faiss_cosine_search_all(vector_store, log_sequence_text, threshold)
 
406
  # 只取前 5 個最相關的片段
407
  retrieved_contents = [f"--- Reference Chunk (sim={score:.3f}) ---\n{doc.page_content}" for i, (doc, score) in enumerate(selected[:5])]
408
  context_text = "\n".join(retrieved_contents)
409
+
410
  rag_instruction = f"""=== RETRIEVED REFERENCE CONTEXT (Cosine ≥ {threshold}) ==={context_text if context_text else 'No relevant reference context found.'}=== END REFERENCE CONTEXT ===ANALYSIS INSTRUCTION: {user_prompt}Based on the provided LOG SEQUENCE and REFERENCE CONTEXT, you must analyze the **entire sequence** to detect any continuous attack chains or evolving threats."""
411
+
412
  log_content_section = f"""=== CURRENT LOG SEQUENCE TO ANALYZE (Window Size: Max {WINDOW_SIZE} logs associated by IP) ==={log_sequence_text}=== END LOG SEQUENCE ==="""
413
+
414
  messages = [
415
  {"role": "system", "content": sys_prompt},
416
  {"role": "user", "content": f"{rag_instruction}\n\n{log_content_section}"}
417
  ]
418
+
419
  try:
420
  # 使用 chat_completion 進行模型呼叫
421
  response_stream = client.chat_completion(
 
428
  if response_stream and response_stream.choices:
429
  return response_stream.choices[0].message.content.strip(), context_text
430
  else: return "Format Error: Model returned empty response or invalid format.", context_text
431
+ except Exception as e:
432
+ return f"Model Error: {str(e)}", context_text
433
+
434
  # =======================================================================
435
  # === 檔案處理區塊 (RAG 檔案) - 保持不變 ===
436
  if rag_uploaded_file:
 
439
  # 清除舊的 vector store 以節省內存
440
  if 'vector_store' in st.session_state:
441
  del st.session_state.vector_store
442
+
443
  with st.spinner(f"正在建立 RAG 參考知識庫 ({rag_uploaded_file.name})..."):
444
  vs, msg = process_file_to_faiss(rag_uploaded_file)
445
  if vs:
 
453
  del st.session_state.vector_store
454
  del st.session_state.rag_current_file_key
455
  st.info("RAG 檔案已移除,已清除相關知識庫。")
456
+
457
  # === 檔案處理區塊 (批量分析檔案 - **已更新** ) ===
458
  if batch_uploaded_file:
459
  batch_file_key = f"batch_{batch_uploaded_file.name}_{batch_uploaded_file.size}"
460
+
461
  if st.session_state.batch_current_file_key != batch_file_key or 'json_data_for_batch' not in st.session_state:
462
  try:
463
  # 清除舊的數據
 
467
  del st.session_state.batch_results
468
  # 使用新的統一解析函式
469
  parsed_data = convert_uploaded_file_to_json_list(batch_uploaded_file)
470
+
471
  if not parsed_data:
472
  raise ValueError(f"{batch_uploaded_file.name} 檔案載入失敗或內容為空。")
473
+
474
  # 儲存處理後的數據
475
  st.session_state.json_data_for_batch = parsed_data
476
  st.session_state.batch_current_file_key = batch_file_key
477
  st.toast(f"檔案已解析並轉換為 {len(parsed_data)} 個 Log 條目。", icon="✅")
478
+
479
  except Exception as e:
480
  st.error(f"檔案解析錯誤: {e}")
481
  if 'json_data_for_batch' in st.session_state:
 
489
  if "batch_results" in st.session_state:
490
  del st.session_state.batch_results
491
  st.info("批量分析檔案已移除,已清除相關數據和結果。")
492
+
493
  # === 執行批量分析邏輯 (已修改為 IP 關聯視窗) ===
494
  if st.session_state.execute_batch_analysis and 'json_data_for_batch' in st.session_state and st.session_state.json_data_for_batch is not None:
495
  st.session_state.execute_batch_analysis = False
496
  start_time = time.time()
497
+
498
  # 這裡必須確保 st.session_state.batch_results 是 List,而不是 None
499
  if 'batch_results' not in st.session_state or st.session_state.batch_results is None:
500
  st.session_state.batch_results = []
 
 
501
 
502
+ st.session_state.batch_results = []
503
+
504
  if inference_client is None:
505
  st.error("Client 未連線,無法執行。")
506
  else:
507
  logs_list = st.session_state.json_data_for_batch
508
+
509
  if logs_list:
510
  vs = st.session_state.get("vector_store", None)
511
+
512
  # 將 Log 條目轉換為 JSON 字串,用於 LLM 輸入
513
  formatted_logs = [json.dumps(log, indent=2, ensure_ascii=False) for log in logs_list]
514
+
515
  analysis_sequences = []
516
+
517
  # --- 核心修改:基於 IP 關聯的 Log Sequence 建構 ---
518
  for i in range(len(formatted_logs)):
519
  current_log_entry = logs_list[i]
520
  current_log_str = formatted_logs[i]
521
+
522
  # 嘗試從當前 Log 條目中提取 IP 地址 (優先 W3C 格式,然後是一般日誌格式)
523
  # 使用者可以根據自己的日誌格式調整這裡的 Key
524
  target_ip = current_log_entry.get('c_ip') or current_log_entry.get('c-ip') or current_log_entry.get('remote_addr') or current_log_entry.get('source_ip')
525
+
526
  sequence_text = []
527
  correlated_logs = []
528
+
529
  if target_ip and target_ip != "-": # 假設 '-' 是 W3C 中的空值
530
+
531
  # 篩選過去的 Log,最多 WINDOW_SIZE - 1 個,且 IP 必須匹配
532
  # 從 i-1 倒序檢查到 0
533
  for j in range(i - 1, -1, -1):
534
  prior_log_entry = logs_list[j]
535
  prior_ip = prior_log_entry.get('c_ip') or prior_log_entry.get('c-ip') or prior_log_entry.get('remote_addr') or prior_log_entry.get('source_ip')
536
+
537
  # 檢查 IP 是否匹配
538
  if prior_ip == target_ip:
539
  # 插入到最前面,保持時間順序
540
  correlated_logs.insert(0, formatted_logs[j])
541
+
542
+ # 限制累積的 Log 數量(不包含當前 Log)
543
+ if len(correlated_logs) >= WINDOW_SIZE - 1:
544
+ break
545
+
546
  # 1. 加入相關聯的 Log (時間較早的)
547
  for j, log_str in enumerate(correlated_logs):
548
  # log_idx 是這些 Log 在 logs_list 中的原始索引 (不完全準確,但提供參考)
549
  sequence_text.append(f"--- Correlated Log Index (IP:{target_ip}) ---\n{log_str}")
550
+
551
  else:
552
  # 如果沒有找到 IP���只分析當前 Log (確保 sequence_text 不是空的)
553
  st.warning(f"Log #{i+1} 找不到 IP 欄位 ({target_ip}),僅分析當前 Log 條目。")
554
+
555
  # 2. 加入當前的目標 Log
556
  sequence_text.append(f"--- TARGET LOG TO ANALYZE (Index {i+1}) ---\n{current_log_str}")
557
+
558
  analysis_sequences.append({
559
  "sequence_text": "\n\n".join(sequence_text),
560
  "target_log_id": i + 1,
561
  "original_log_entry": logs_list[i]
562
  })
563
+
564
  # --- LLM 執行迴圈 ---
565
  total_sequences = len(analysis_sequences)
566
  st.header(f"⚡ 批量分析執行中 (IP 關聯視窗 $N={WINDOW_SIZE}$)...")
567
  progress_bar = st.progress(0, text=f"準備處理 {total_sequences} 個序列...")
568
  results_container = st.container()
569
+
570
  for i, seq_data in enumerate(analysis_sequences):
571
  log_id = seq_data["target_log_id"]
572
  progress_bar.progress((i + 1) / total_sequences, text=f"Processing {i + 1}/{total_sequences} (Log #{log_id})...")
573
+
574
  try:
575
  response, retrieved_ctx = generate_rag_response_hf_for_log(
576
  client=inference_client,
 
584
  temperature=temperature,
585
  top_p=top_p
586
  )
587
+
588
  item = {
589
  "log_id": log_id,
590
  "log_content": seq_data["original_log_entry"],
 
592
  "analysis_result": response,
593
  "context": retrieved_ctx
594
  }
595
+
596
  st.session_state.batch_results.append(item)
597
+
598
+ with results_container:
599
+ # 呈現 LLM 分析結果
600
+ is_high = any(x in response.lower() for x in ['high-risk detected'])
601
+ if is_high:
602
+ st.subheader(f"Log/Alert #{item['log_id']} (IP Correlated Analysis)")
 
 
 
603
  with st.expander("序列內容 (JSON Format)"):
604
  st.code(item["sequence_analyzed"], language='json')
 
 
 
605
  st.error(item['analysis_result'])
606
+ else:
607
+ # 增加 Medium 判斷
608
+ is_medium = any(x in response.lower() for x in ['medium-risk detected'])
609
+ if is_medium:
610
+ st.subheader(f"Log/Alert #{item['log_id']} (IP Correlated Analysis)")
611
+ with st.expander("序列內容 (JSON Format)"):
612
+ st.code(item["sequence_analyzed"], language='json')
613
+ st.warning(item['analysis_result'])
614
+
615
+ if item['context']:
616
+ with st.expander("參考 RAG 片段"): st.code(item['context'])
617
+ st.markdown("---")
618
+
619
  except Exception as e:
620
  st.error(f"Error Log {log_id}: {e}")
621
+
622
  end_time = time.time()
623
  progress_bar.empty()
624
  st.success(f"完成!耗時 {end_time - start_time:.2f} 秒。")
625
  else:
626
  st.error("無法提取有效 Log,請檢查檔案格式。")
627
 
628
+ # === 顯示結果 (歷史紀錄) - 保持不變但加固了 session state 檢查 ===
629
  if st.session_state.get("batch_results") and isinstance(st.session_state.batch_results, list) and st.session_state.batch_results and not st.session_state.execute_batch_analysis:
630
+ st.header("⚡ 歷史分析結果")
631
+
632
+ high_risk_data = []
633
  high_risk_items = []
634
+
 
635
  for item in st.session_state.batch_results:
636
  # 檢查 analysis_result 中是否包含 'High-risk detected' (不區分大小寫)
637
  is_high_risk = 'high-risk detected!' in item['analysis_result'].lower()
638
+
 
639
  if is_high_risk:
640
  high_risk_items.append(item)
 
 
 
 
 
 
641
 
642
+ # --- 為 CSV 報告準備數據 ---
643
+ log_content_str = json.dumps(item["log_content"], ensure_ascii=False)
644
+ analysis_result_clean = item['analysis_result'].replace('\n', ' | ')
 
 
 
 
 
 
 
 
 
 
 
 
 
645
 
646
+ high_risk_data.append({
647
+ "Log_ID": item['log_id'],
648
+ "Risk_Level": "HIGH_RISK",
649
+ "Log_Content": log_content_str,
650
+ "AI_Analysis_Result": analysis_result_clean
651
+ })
652
+
653
+ # 顯示 High-Risk 報告的下載按鈕 (改為 CSV 邏輯)
654
+ if high_risk_items:
655
+ st.success(f"✅ 檢測到 {len(high_risk_items)} 條高風險 Log/Alert。")
656
+
657
+ # --- 構建 CSV 內容 ---
 
 
 
 
 
 
 
 
 
 
 
 
658
  csv_output = io.StringIO()
659
  csv_output.write("Log_ID,Risk_Level,Log_Content,AI_Analysis_Result\n")
660
+
661
  def escape_csv(value):
662
  # 替換內容中的所有雙引號為兩個雙引號,然後用雙引號包圍
663
  return f'"{str(value).replace('"', '""')}"'
664
+
665
+ for row in high_risk_data:
666
  line = ",".join([
667
  str(row["Log_ID"]),
668
  row["Risk_Level"],
 
670
  escape_csv(row["AI_Analysis_Result"])
671
  ]) + "\n"
672
  csv_output.write(line)
673
+
674
  csv_content = csv_output.getvalue()
675
+
676
+ # 顯示 CSV 報告的下載按鈕
677
  st.download_button(
678
+ "📥 下載 **高風險** 分析報告 (.csv)",
679
  csv_content,
680
+ "high_risk_report.csv",
681
  "text/csv"
682
  )
683
  else:
684
+ st.info("👍 未檢測到任何標註為 High-risk detected 的 Log/Alert。")
685
+