s880453 commited on
Commit
ced9cee
·
verified ·
1 Parent(s): cd651e9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +674 -283
app.py CHANGED
@@ -2,10 +2,11 @@ import gradio as gr
2
  import os
3
  import json
4
  import time
 
5
  from datetime import datetime
6
  import numpy as np
7
- from datasets import load_dataset
8
- from huggingface_hub import HfApi
9
  import torch
10
  from transformers import AutoTokenizer, AutoModel
11
  from openai import OpenAI
@@ -14,22 +15,34 @@ import io
14
  from typing import List, Dict, Any, Optional, Tuple
15
  from dataclasses import dataclass, field
16
  from enum import Enum
 
 
 
 
 
17
 
18
  # ==========================================
19
  # 環境變數設定
20
  # ==========================================
21
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
22
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
 
23
 
24
  # 資料集配置
25
  DATASET_NAME = "s880453/interview-transcripts-vectorized"
 
26
  EMBEDDING_MODEL = "intfloat/multilingual-e5-large"
27
 
28
  # 採訪者名單(需要排除)
29
  INTERVIEWERS = ["徐美苓", "許弘諺", "郭禹彤"]
30
 
 
 
 
 
 
31
  # ==========================================
32
- # 結構化數據模型(Pydantic 風格)
33
  # ==========================================
34
  @dataclass
35
  class SearchResult:
@@ -44,23 +57,15 @@ class SearchResult:
44
  relevance_reasoning: str = ""
45
 
46
  @dataclass
47
- class RerankingResult:
48
- """重排序結果"""
49
- reasoning: str
50
- speaker_relevance: str
51
- content_relevance: str
52
- context_relevance: str
53
- relevance_score: float
54
-
55
- @dataclass
56
- class QuestionAnswerPair:
57
- """問答對結構"""
58
- question: str
59
- answers: List[str]
60
- raw_contexts: List[str] # 原始 RAG 內容
61
- relevant_turn_indexes: List[int]
62
- confidence_scores: List[float]
63
- search_results: List[SearchResult]
64
 
65
  # ==========================================
66
  # 全域變數
@@ -70,15 +75,18 @@ embeddings = None
70
  tokenizer = None
71
  model = None
72
  openai_client = None
 
73
  all_speakers = []
74
  init_success = False
 
 
75
 
76
  # ==========================================
77
  # 初始化函數
78
  # ==========================================
79
  def initialize_system():
80
  """初始化系統"""
81
- global dataset, embeddings, tokenizer, model, openai_client, all_speakers, init_success
82
 
83
  try:
84
  print("🔄 正在初始化系統...")
@@ -91,6 +99,22 @@ def initialize_system():
91
  print("⚠️ 未設定 OpenAI API Key")
92
  return False, "請設定 OPENAI_API_KEY"
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  # 載入資料集
95
  print(f"📊 正在載入資料集: {DATASET_NAME}")
96
  dataset = load_dataset(DATASET_NAME, split="train", token=HF_TOKEN)
@@ -126,7 +150,60 @@ def initialize_system():
126
  return False, error_msg
127
 
128
  # ==========================================
129
- # 向量搜尋函數(結合 speaker + content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  # ==========================================
131
  def average_pool(last_hidden_states, attention_mask):
132
  """Average pooling for embeddings"""
@@ -134,12 +211,10 @@ def average_pool(last_hidden_states, attention_mask):
134
  return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
135
 
136
  def generate_query_embedding(query_text):
137
- """生成查詢向量 - 使用正確的前綴格式"""
138
  try:
139
- # 添加查詢前綴(按照 multilingual-e5-large 的要求)
140
  query_with_prefix = f"query: {query_text}"
141
 
142
- # Tokenize
143
  inputs = tokenizer(
144
  [query_with_prefix],
145
  max_length=512,
@@ -148,11 +223,9 @@ def generate_query_embedding(query_text):
148
  return_tensors='pt'
149
  )
150
 
151
- # 生成嵌入
152
  with torch.no_grad():
153
  outputs = model(**inputs)
154
  query_embedding = average_pool(outputs.last_hidden_state, inputs['attention_mask'])
155
- # L2 正規化
156
  query_embedding = torch.nn.functional.normalize(query_embedding, p=2, dim=1)
157
 
158
  return query_embedding.cpu().numpy()[0]
@@ -169,35 +242,14 @@ def build_reranking_prompt(query: str, search_results: List[Dict]) -> str:
169
  你將收到一個查詢和幾個檢索到的訪談片段。你的任務是根據片段與查詢的相關性來評估和評分每個片段。
170
 
171
  評分指南:
172
- 1. 推理:分析片段中的關鍵信息及其與查詢的關係。
173
- 2. 相關性評分(0到1):
174
- - 0 = 完全無關
175
- - 0.3 = 輕微相關
176
- - 0.5 = 中等相關
177
- - 0.7 = 相關
178
- - 0.9 = 高度相關
179
- - 1 = 完全相關
180
-
181
- 特別注意:
182
- - 必須排除採訪者(徐美苓、許弘諺、郭禹彤)的一般回覆
183
- - 檢查上下文相關性(turn_index前後範圍)
184
- - 評估多重主題匹配的可能性
185
 
186
- 請為每個搜尋結果提供JSON格式的評分:
187
- {
188
- "results": [
189
- {
190
- "index": 0,
191
- "reasoning": "分析原因",
192
- "speaker_relevance": "發言人相關性",
193
- "content_relevance": "內容相關性",
194
- "context_relevance": "上下文相關性",
195
- "relevance_score": 0.8
196
- }
197
- ]
198
- }"""
199
 
200
- # 構建搜尋結果文本
201
  results_text = f"查詢:{query}\n\n檢索結果:\n"
202
  for i, result in enumerate(search_results):
203
  results_text += f"\n結果 {i}:\n"
@@ -213,7 +265,7 @@ def intelligent_routing_and_reranking(query: str, selected_speakers: List[str],
213
  return []
214
 
215
  try:
216
- # Step 1: 向量檢索 (Top-30 候選)
217
  query_vector = generate_query_embedding(query)
218
  if query_vector is None:
219
  return []
@@ -221,15 +273,14 @@ def intelligent_routing_and_reranking(query: str, selected_speakers: List[str],
221
  # Step 2: 計算相似度並過濾
222
  initial_results = []
223
  for i, item in enumerate(dataset):
224
- # 智慧路由:排除採訪者
225
  if item['speaker'] in INTERVIEWERS:
226
  continue
227
 
228
- # 重要修正:嚴格的受訪者過濾
229
- # 如果有選擇特定受訪者,只使用該受訪者的資料
230
  if selected_speakers and len(selected_speakers) > 0:
231
  if item['speaker'] not in selected_speakers:
232
- continue # 跳過不在選擇列表中的受訪者
233
 
234
  # 計算向量相似度
235
  item_vector = np.array(item['embedding'])
@@ -251,10 +302,10 @@ def intelligent_routing_and_reranking(query: str, selected_speakers: List[str],
251
  if not candidates:
252
  return []
253
 
254
- # Step 3: LLM 重排序
255
- rerank_prompt = build_reranking_prompt(query, candidates[:10]) # 只重排序前10個
256
-
257
  try:
 
 
258
  response = openai_client.chat.completions.create(
259
  model="gpt-4o-mini",
260
  messages=[
@@ -267,19 +318,17 @@ def intelligent_routing_and_reranking(query: str, selected_speakers: List[str],
267
 
268
  rerank_results = json.loads(response.choices[0].message.content)
269
 
270
- # Step 4: 加權計分 (0.3 * vector + 0.7 * llm)
271
  final_results = []
272
  for i, candidate in enumerate(candidates[:10]):
273
- llm_score = 0.5 # 預設分數
274
 
275
- # 從 LLM 結果中找到對應的分數
276
  if 'results' in rerank_results:
277
  for r in rerank_results['results']:
278
  if r.get('index') == i:
279
  llm_score = r.get('relevance_score', 0.5)
280
  break
281
 
282
- # 計算加權分數
283
  weighted_score = 0.3 * candidate['vector_score'] + 0.7 * llm_score
284
 
285
  final_results.append(SearchResult(
@@ -292,7 +341,7 @@ def intelligent_routing_and_reranking(query: str, selected_speakers: List[str],
292
  weighted_score=weighted_score
293
  ))
294
 
295
- # 加入剩餘的候選(未經 LLM 重排序的)
296
  for candidate in candidates[10:]:
297
  final_results.append(SearchResult(
298
  text=candidate['text'],
@@ -307,14 +356,14 @@ def intelligent_routing_and_reranking(query: str, selected_speakers: List[str],
307
  # 按加權分數排序
308
  final_results.sort(key=lambda x: x.weighted_score, reverse=True)
309
 
310
- # Step 5: 上下文擴展(只擴展相同受訪者的內容)
311
- expanded_results = expand_context_by_turn_index(final_results[:5], selected_speakers)
312
 
313
- return expanded_results
314
 
315
  except Exception as e:
316
- print(f"LLM 重排序失敗,使用向量分數: {str(e)}")
317
- # 降級處理:只使用向量分數
318
  return [SearchResult(
319
  text=c['text'],
320
  speaker=c['speaker'],
@@ -323,110 +372,274 @@ def intelligent_routing_and_reranking(query: str, selected_speakers: List[str],
323
  vector_score=c['vector_score'],
324
  llm_score=0.0,
325
  weighted_score=c['vector_score']
326
- ) for c in candidates[:top_k]]
327
 
328
  except Exception as e:
329
  print(f"智慧路由失敗: {str(e)}")
330
  return []
331
 
332
- def expand_context_by_turn_index(search_results: List[SearchResult], selected_speakers: List[str] = None, context_window: int = 10) -> List[SearchResult]:
333
- """根據 turn_index 擴展上下文 - 只擴展相同受訪者的相關內容"""
334
- expanded_results = []
335
- added_indexes = set()
336
-
337
- # 只保留主要結果,不進行上下文擴展(避免引入雜訊)
338
- for result in search_results:
339
- # 添加原始結果
340
- key = f"{result.speaker}_{result.turn_index}"
341
- if key not in added_indexes:
342
- expanded_results.append(result)
343
- added_indexes.add(key)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
 
345
- # 移除上下文擴展邏輯,因為會引入無關內容
346
- # 如果需要上下文,應該基於語義相似度而非 turn_index 距離
 
 
 
347
 
348
- # 再次過濾,確保只包含選定的受訪者
349
- if selected_speakers and len(selected_speakers) > 0:
350
- filtered_results = [r for r in expanded_results if r.speaker in selected_speakers]
351
- return filtered_results
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
352
 
353
- return expanded_results
 
 
354
 
355
  # ==========================================
356
- # RAG 對話函數(每次獨立調用 API)
357
  # ==========================================
358
  def rag_chat(question, selected_speakers, history):
359
- """RAG 對話處理 - 每次獨立調用避免幻覺"""
360
  if not init_success:
361
  return history + [[question, "系統尚未初始化,請稍後再試。"]]
362
 
363
  try:
364
  # 執行智慧路由與重排序
365
- search_results = intelligent_routing_and_reranking(question, selected_speakers, top_k=20)
 
 
 
366
 
367
- if not search_results:
368
  return history + [[question, "未找到相關內容,請嘗試其他問題。"]]
369
 
370
- # 構建上下文(包含原始 RAG 內容)
371
  context = "相關訪談內容:\n\n"
372
  raw_contexts = []
373
 
374
- for i, result in enumerate(search_results[:5], 1):
375
- context += f"[片段 {i}]\n"
376
  context += f"發言人:{result.speaker}\n"
377
  context += f"內容:{result.text}\n"
378
- context += f"相關性分數:向量={result.vector_score:.3f}, LLM={result.llm_score:.3f}, 加權={result.weighted_score:.3f}\n\n"
379
 
380
- # 保存原始內容 - 確保文本存在
381
  if result.text:
382
  raw_context_text = f"[{result.speaker} - Turn {result.turn_index}]: {result.text}"
383
  raw_contexts.append(raw_context_text)
384
 
385
- # 確保有原始內容
386
  if not raw_contexts:
387
  raw_contexts = ["未能提取原始內容"]
388
 
389
- # 構建 GPT prompt(每次獨立,不包含歷史)
390
  prompt = f"""基於以下訪談內容回答問題。請提供準確、完整的回答。
391
 
392
  {context}
393
 
394
- 問題:{question}
395
-
396
- 要求:
397
- 1. 基於提供的訪談內容回答
398
- 2. 引用具體的發言人和內容
399
- 3. 如果內容不足以回答,請明確說明"""
400
-
401
- # 調用 GPT(每次獨立調用)
402
- response = openai_client.chat.completions.create(
403
- model="gpt-4o-mini",
404
- messages=[
405
- {"role": "system", "content": "你是一個專業的訪談分析助手。只基於提供的內容回答,不要添加額外信息。"},
406
- {"role": "user", "content": prompt}
407
- ],
408
- temperature=0.1
409
- )
410
 
411
- answer = response.choices[0].message.content
 
412
 
413
- # 添加原始 RAG 內容(完整顯示,不截斷)
414
- answer_with_sources = f"{answer}\n\n---\n📚 **原始 RAG 來源:**\n"
415
- for i, raw_context in enumerate(raw_contexts[:3], 1):
416
- # 確保 raw_context 是字串且有內容
417
  if raw_context and raw_context != "未能提取原始內容":
418
- # 完整顯示內容,不截斷
419
- answer_with_sources += f"\n**來源 {i}:**\n{raw_context}\n"
420
  else:
421
- answer_with_sources += f"\n**來源 {i}:** 無內容\n"
422
 
423
  return history + [[question, answer_with_sources]]
424
 
425
  except Exception as e:
426
  return history + [[question, f"處理過程中發生錯誤:{str(e)}"]]
427
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
428
  # ==========================================
429
- # 訪綱填答函數(包含原始 RAG 內容)
430
  # ==========================================
431
  def parse_word_document(file_path):
432
  """解析 Word 文檔中的問題"""
@@ -454,20 +667,19 @@ def extract_speaker_from_filename(filename, available_speakers):
454
  base_name = os.path.basename(filename)
455
  base_name_no_ext = os.path.splitext(base_name)[0]
456
 
457
- # 檢查檔名中是否包含任何受訪者名稱
458
  for speaker in available_speakers:
459
  if speaker in base_name_no_ext:
460
  return [speaker]
461
 
462
- return None # 如果沒有找到,返回 None
463
 
464
- def single_interviewee_guide_filling(file_path, selected_speakers, file_name=None):
465
- """單一受訪者訪綱填答 - 整合冠軍策略"""
466
  if not init_success:
467
  return None, "系統尚未初始化"
468
 
469
  try:
470
- # 如果提供了檔案名稱,嘗試從中提取受訪者
471
  if file_name:
472
  detected_speakers = extract_speaker_from_filename(file_name, all_speakers)
473
  if detected_speakers:
@@ -480,90 +692,47 @@ def single_interviewee_guide_filling(file_path, selected_speakers, file_name=Non
480
  if not questions:
481
  return None, "未能從文檔中提取問題"
482
 
 
 
 
 
 
 
 
 
483
  # 創建新的 Word 文檔
484
  output_doc = Document()
485
  output_doc.add_heading('訪談訪綱 - AI 智慧填答', 0)
486
  output_doc.add_paragraph(f'處理時間:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
487
  output_doc.add_paragraph(f'原始檔案:{file_name if file_name else "未知"}')
488
  output_doc.add_paragraph(f'選擇的受訪者:{", ".join(selected_speakers) if selected_speakers else "全部"}')
489
- output_doc.add_paragraph(f'使用技術:Multilingual-E5-Large + GPT-4o-mini + 冠軍級 RAG')
 
490
  output_doc.add_paragraph('')
491
 
492
- # 處理每個問題(每個問題獨立調用 API)
493
- for i, question in enumerate(questions[:10], 1):
494
  output_doc.add_heading(f'問題 {i}', level=1)
495
- output_doc.add_paragraph(question)
496
-
497
- # 使用智慧路由與重排序檢索
498
- search_results = intelligent_routing_and_reranking(question, selected_speakers, top_k=15)
499
-
500
- # 過濾掉低相關性的結果(相關性分數低於 0.4 的視為雜訊)
501
- filtered_results = [r for r in search_results if r.weighted_score >= 0.4]
502
 
503
- if filtered_results:
504
- # 構建上下文
505
- context = ""
506
- raw_contexts = []
507
-
508
- for j, result in enumerate(filtered_results[:5]):
509
- context += f"[片段 {j+1}]\n"
510
- context += f"發言人:{result.speaker}\n"
511
- context += f"內容:{result.text}\n"
512
- context += f"相關性:向量={result.vector_score:.3f}, LLM={result.llm_score:.3f}\n\n"
513
-
514
- raw_contexts.append({
515
- 'speaker': result.speaker,
516
- 'text': result.text,
517
- 'turn_index': result.turn_index,
518
- 'score': result.weighted_score
519
- })
520
-
521
- # 獨立調用 GPT 生成回答
522
- prompt = f"""基於以下訪談內容回答訪綱問題:
523
-
524
- {context}
525
-
526
- 問題:{question}
527
-
528
- 請提供:
529
- 1. 主要回答
530
- 2. 不同受訪者的觀點(如果有)
531
- 3. 具體引述"""
532
-
533
- response = openai_client.chat.completions.create(
534
- model="gpt-4o-mini",
535
- messages=[
536
- {"role": "system", "content": "你是訪談分析專家。基於提供的內容準確回答。"},
537
- {"role": "user", "content": prompt}
538
- ],
539
- temperature=0.1
540
- )
541
-
542
- answer = response.choices[0].message.content
543
-
544
- # 添加 AI 回答
545
  output_doc.add_heading('AI 分析回答:', level=2)
546
- for line in answer.split('\n'):
547
  if line.strip():
548
  output_doc.add_paragraph(line)
549
 
550
- # 添加原始 RAG 內容(完整顯示,不省略)
551
- output_doc.add_heading('原始 RAG 向量檢索內容:', level=2)
552
- for j, raw in enumerate(raw_contexts[:3], 1):
553
  p = output_doc.add_paragraph()
554
- p.add_run(f"{j}. [{raw['speaker']} - Turn {raw['turn_index']}] ").bold = True
555
  p.add_run(f"(相關性: {raw['score']:.3f})\n")
556
- # 顯示完整內容,不截斷
557
- p.add_run(raw['text'])
558
  else:
559
- output_doc.add_paragraph("未找到相關內容")
560
 
561
- output_doc.add_page_break() # 分頁
562
-
563
- # 添加未使用內容分析(如果是單一受訪者)
564
- if len(selected_speakers) == 1:
565
- output_doc.add_heading('補充:可能相關但未被問及的內容', level=1)
566
- # 這裡可以加入額外的分析邏輯
567
 
568
  # 保存文檔
569
  output_buffer = io.BytesIO()
@@ -577,64 +746,146 @@ def single_interviewee_guide_filling(file_path, selected_speakers, file_name=Non
577
  with open(output_filename, 'wb') as f:
578
  f.write(output_buffer.getvalue())
579
 
580
- return output_filename, f"訪綱填答完成!檔案:{output_filename}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
581
 
582
  except Exception as e:
583
  return None, f"處理失敗:{str(e)}"
584
 
585
- def batch_process_guides(files, default_speakers):
586
- """批量處理多個訪綱檔案"""
587
  if not init_success:
588
  return [], "系統尚未初始化"
589
 
590
  results = []
591
  processed_files = []
 
592
 
593
  try:
594
- total_files = len(files)
595
  print(f"開始批量處理 {total_files} 個檔案")
596
 
597
- for idx, file in enumerate(files, 1):
 
 
 
 
 
 
 
 
 
598
  try:
599
  file_name = file.name if hasattr(file, 'name') else str(file)
600
- print(f"\n處理檔案 {idx}/{total_files}: {file_name}")
601
 
602
- # 從檔名中檢測受訪者
603
  detected_speakers = extract_speaker_from_filename(file_name, all_speakers)
604
 
605
  if detected_speakers:
606
  speakers_to_use = detected_speakers
607
- status_msg = f"檔案 {idx}: 從檔名檢測到受訪者 {detected_speakers[0]}"
608
  else:
609
  speakers_to_use = default_speakers
610
- status_msg = f"檔案 {idx}: 使用預設受訪者"
611
 
612
  print(status_msg)
613
- results.append(status_msg)
614
 
615
- # 處理單個檔案
616
  output_file, process_status = single_interviewee_guide_filling(
617
  file.name if hasattr(file, 'name') else file,
618
  speakers_to_use,
619
- file_name
 
620
  )
621
 
622
  if output_file:
623
- processed_files.append(output_file)
624
- results.append(f"✅ {file_name} 處理成功 -> {output_file}")
 
 
 
 
625
  else:
626
- results.append(f"❌ {file_name} 處理失敗: {process_status}")
627
-
628
- # 避免系統過載,每處理一個檔案休息一下
629
- time.sleep(1)
630
-
 
631
  except Exception as e:
632
- error_msg = f"❌ 檔案 {idx} 處理錯誤: {str(e)}"
633
- print(error_msg)
634
- results.append(error_msg)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
635
 
636
  # 彙總結果
637
- summary = f"\n處理完成!\n成功: {len(processed_files)}/{total_files} 個檔案\n"
 
 
638
  summary += "\n詳細結果:\n" + "\n".join(results)
639
 
640
  return processed_files, summary
@@ -655,22 +906,23 @@ def create_interface():
655
  .gradio-container {
656
  font-family: 'Microsoft JhengHei', sans-serif;
657
  }
658
- .markdown-text {
659
- font-size: 16px;
660
  }
661
  """
662
  ) as app:
663
  # 標題
664
  gr.Markdown("""
665
- # 🎙️ 訪談轉錄稿智慧分析系統
666
 
667
- **技術架構:** Multilingual-E5-Large + GPT-4o-mini + 冠軍級 RAG 策略
668
 
669
  **核心功能:**
670
- - 🔍 智慧語義搜尋與重排序
671
- - 💬 AI 對話(每次獨立調用避免幻覺)
672
- - 📝 訪綱自動填答(含原始 RAG 內容)
673
- - 📊 加權評分機制(0.3×向量 + 0.7×LLM
 
674
  """)
675
 
676
  # 系統狀態
@@ -686,7 +938,7 @@ def create_interface():
686
  with gr.Tabs():
687
  # Tab 1: AI 對話
688
  with gr.Tab("💬 AI 對話"):
689
- gr.Markdown("### 智慧問答系統(每次獨立調用 API)")
690
 
691
  with gr.Row():
692
  with gr.Column(scale=1):
@@ -714,7 +966,17 @@ def create_interface():
714
 
715
  with gr.Row():
716
  clear_btn = gr.Button("清除對話")
717
- gr.Markdown("*每個問題都會獨立調用 API,避免產生幻覺*")
 
 
 
 
 
 
 
 
 
 
718
 
719
  # Tab 2: 訪綱填答
720
  with gr.Tab("📝 訪綱填答"):
@@ -722,15 +984,11 @@ def create_interface():
722
  ### 智慧訪綱填答系統
723
 
724
  **特色功能:**
725
- - 支援批量處理(最多15個檔案)
726
- - 自動從檔名識別受訪者
727
- - 使用冠軍級 RAG 策略
728
- - 每個問題獨立處理
729
- - 顯示原始 RAG 檢索內容
730
-
731
- **檔名識別規則:**
732
- - 如果檔名包含受訪者姓名(如:`訪綱_陳美玲.docx`),系統會自動使用該受訪者的資料
733
- - 如果檔名未包含受訪者姓名,則使用您勾選的受訪者
734
  """)
735
 
736
  with gr.Row():
@@ -741,7 +999,7 @@ def create_interface():
741
  info="檔名中有受訪者名稱時會自動覆蓋此選擇"
742
  )
743
 
744
- # 單檔上傳(保留原功能)
745
  with gr.Accordion("單檔處理", open=False):
746
  single_file_input = gr.File(
747
  label="上傳單個訪綱 (Word 格式)",
@@ -749,29 +1007,38 @@ def create_interface():
749
  )
750
  single_process_btn = gr.Button("處理單檔", variant="secondary")
751
 
752
- # 批量上傳(新功能)
753
  batch_file_input = gr.File(
754
  label="批量上傳訪綱(最多15個 Word 檔案)",
755
  file_types=[".docx"],
756
  file_count="multiple"
757
  )
758
 
759
- batch_process_btn = gr.Button("🚀 批量處理所有檔案", variant="primary", size="lg")
760
 
761
  with gr.Column():
 
 
 
762
  process_status = gr.Textbox(
763
  label="處理狀態",
764
  interactive=False,
765
  lines=10
766
  )
767
 
768
- # 單檔下載
 
 
 
 
 
 
 
769
  single_download_file = gr.File(
770
  label="下載單檔結果",
771
  visible=False
772
  )
773
 
774
- # 批量下載
775
  batch_download_files = gr.File(
776
  label="下載所有結果",
777
  visible=False,
@@ -781,23 +1048,32 @@ def create_interface():
781
  # 技術細節
782
  with gr.Accordion("🔧 技術細節", open=False):
783
  gr.Markdown("""
784
- ### 冠軍級 RAG 技術實現
785
-
786
- **1. 向量化處理**
787
- - 模型:Multilingual-E5-Large
788
- - 格式:結合 speaker + content
789
- - 前綴:query: / passage:
790
-
791
- **2. 智慧路由與重排序**
792
- - 初步檢索:Top-30 向量相似度
793
- - LLM 重排序:GPT-4o-mini 評分
794
- - 加權計算:0.3×向量 + 0.7×LLM
795
- - 上下文擴展:±10 turn_index
796
-
797
- **3. 防止幻覺機制**
798
- - 每次問題獨立調用 API
799
- - 不傳遞歷史對話上下文
800
- - 顯示原始 RAG 來源
 
 
 
 
 
 
 
 
 
801
  """)
802
 
803
  # 事件處理
@@ -810,34 +1086,97 @@ def create_interface():
810
  def clear_chat():
811
  return []
812
 
813
- def process_single_guide(file, speakers):
814
- """處理單個檔案"""
 
 
 
 
 
 
 
 
 
 
 
 
 
815
  if not file:
816
- return "請上傳文件", gr.File(visible=False)
 
 
 
 
817
 
818
- result_file, status = single_interviewee_guide_filling(file.name, speakers, file.name)
 
 
 
 
 
 
 
 
819
 
820
  if result_file:
821
- return status, gr.File(value=result_file, visible=True)
 
 
 
 
 
 
 
822
  else:
823
- return status, gr.File(visible=False)
 
 
 
 
 
 
 
824
 
825
- def process_batch_guides(files, speakers):
826
- """批量處理多個檔案"""
827
  if not files:
828
- return "請上傳至少一個檔案", gr.File(visible=False)
 
 
 
 
829
 
830
- # 限制最多15個檔案
831
  if len(files) > 15:
832
- return f"檔案數量超過限制(最多15個),您上傳了 {len(files)} 個", gr.File(visible=False)
 
 
 
 
 
 
 
833
 
834
  # 批量處理
835
- processed_files, status = batch_process_guides(files, speakers)
836
 
837
  if processed_files:
838
- return status, gr.File(value=processed_files, visible=True, file_count="multiple")
 
 
 
 
 
 
 
839
  else:
840
- return status, gr.File(visible=False)
 
 
 
 
 
 
 
841
 
842
  def update_status():
843
  success, message = initialize_system()
@@ -864,18 +1203,38 @@ def create_interface():
864
 
865
  clear_btn.click(clear_chat, outputs=[chatbot])
866
 
 
 
 
 
 
 
867
  # 單檔處理
868
  single_process_btn.click(
869
- process_single_guide,
870
  inputs=[single_file_input, guide_speakers],
871
- outputs=[process_status, single_download_file]
 
 
 
 
 
 
 
872
  )
873
 
874
  # 批量處理
875
  batch_process_btn.click(
876
- process_batch_guides,
877
  inputs=[batch_file_input, guide_speakers],
878
- outputs=[process_status, batch_download_files]
 
 
 
 
 
 
 
879
  )
880
 
881
  init_btn.click(
@@ -888,6 +1247,12 @@ def create_interface():
888
  update_status,
889
  outputs=[status_text, speaker_selector, guide_speakers]
890
  )
 
 
 
 
 
 
891
 
892
  return app
893
 
@@ -895,6 +1260,32 @@ def create_interface():
895
  # 主程式入口
896
  # ==========================================
897
  if __name__ == "__main__":
898
- # 創建並啟動應用
899
  app = create_interface()
900
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import os
3
  import json
4
  import time
5
+ import asyncio
6
  from datetime import datetime
7
  import numpy as np
8
+ from datasets import load_dataset, Dataset as HFDataset
9
+ from huggingface_hub import HfApi, upload_file, create_repo
10
  import torch
11
  from transformers import AutoTokenizer, AutoModel
12
  from openai import OpenAI
 
15
  from typing import List, Dict, Any, Optional, Tuple
16
  from dataclasses import dataclass, field
17
  from enum import Enum
18
+ from concurrent.futures import ThreadPoolExecutor, as_completed
19
+ import threading
20
+ from tqdm import tqdm
21
+ import traceback
22
+ import queue
23
 
24
  # ==========================================
25
  # 環境變數設定
26
  # ==========================================
27
  HF_TOKEN = os.environ.get("HF_TOKEN", "")
28
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
29
+ ACCESS_PASSWORD = os.environ.get("ACCESS_PASSWORD", "netzero2025") # 密碼保護
30
 
31
  # 資料集配置
32
  DATASET_NAME = "s880453/interview-transcripts-vectorized"
33
+ OUTPUT_DATASET = "s880453/interview-outputs" # 輸出資料集
34
  EMBEDDING_MODEL = "intfloat/multilingual-e5-large"
35
 
36
  # 採訪者名單(需要排除)
37
  INTERVIEWERS = ["徐美苓", "許弘諺", "郭禹彤"]
38
 
39
+ # 並行處理設定
40
+ MAX_WORKERS = 5 # 最多 5 個並行處理
41
+ MAX_RETRIES = 3 # 最多重試 3 次
42
+ RELEVANCE_THRESHOLD = 0.4 # 相關性門檻
43
+
44
  # ==========================================
45
+ # 結構化數據模型
46
  # ==========================================
47
  @dataclass
48
  class SearchResult:
 
57
  relevance_reasoning: str = ""
58
 
59
  @dataclass
60
+ class ProcessingStatus:
61
+ """處理狀態追蹤"""
62
+ total_items: int = 0
63
+ completed_items: int = 0
64
+ failed_items: int = 0
65
+ current_item: str = ""
66
+ start_time: float = 0.0
67
+ estimated_time: float = 0.0
68
+ errors: List[str] = field(default_factory=list)
 
 
 
 
 
 
 
 
69
 
70
  # ==========================================
71
  # 全域變數
 
75
  tokenizer = None
76
  model = None
77
  openai_client = None
78
+ hf_api = None
79
  all_speakers = []
80
  init_success = False
81
+ processing_status = ProcessingStatus()
82
+ status_lock = threading.Lock()
83
 
84
  # ==========================================
85
  # 初始化函數
86
  # ==========================================
87
  def initialize_system():
88
  """初始化系統"""
89
+ global dataset, embeddings, tokenizer, model, openai_client, all_speakers, init_success, hf_api
90
 
91
  try:
92
  print("🔄 正在初始化系統...")
 
99
  print("⚠️ 未設定 OpenAI API Key")
100
  return False, "請設定 OPENAI_API_KEY"
101
 
102
+ # 初始化 Hugging Face API
103
+ hf_api = HfApi(token=HF_TOKEN)
104
+
105
+ # 確保輸出資料集存在
106
+ try:
107
+ create_repo(
108
+ repo_id=OUTPUT_DATASET,
109
+ repo_type="dataset",
110
+ private=True,
111
+ exist_ok=True,
112
+ token=HF_TOKEN
113
+ )
114
+ print(f"✅ 輸出資料集 {OUTPUT_DATASET} 已準備")
115
+ except Exception as e:
116
+ print(f"⚠️ 創建輸出資料集時出現問題: {e}")
117
+
118
  # 載入資料集
119
  print(f"📊 正在載入資料集: {DATASET_NAME}")
120
  dataset = load_dataset(DATASET_NAME, split="train", token=HF_TOKEN)
 
150
  return False, error_msg
151
 
152
  # ==========================================
153
+ # HF Dataset 上傳函數
154
+ # ==========================================
155
+ def upload_to_hf_dataset(file_path, file_type="guide", metadata=None):
156
+ """上傳檔案到 HF Dataset"""
157
+ try:
158
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
159
+
160
+ # 決定路徑
161
+ if file_type == "guide":
162
+ repo_path = f"guide_outputs/{os.path.basename(file_path)}"
163
+ elif file_type == "chat":
164
+ repo_path = f"chat_exports/{os.path.basename(file_path)}"
165
+ else:
166
+ repo_path = f"others/{os.path.basename(file_path)}"
167
+
168
+ # 上傳檔案
169
+ upload_file(
170
+ path_or_fileobj=file_path,
171
+ path_in_repo=repo_path,
172
+ repo_id=OUTPUT_DATASET,
173
+ repo_type="dataset",
174
+ token=HF_TOKEN
175
+ )
176
+
177
+ print(f"✅ 檔案已上傳到 HF Dataset: {repo_path}")
178
+
179
+ # 更新 metadata
180
+ if metadata:
181
+ metadata_path = f"metadata/{timestamp}.json"
182
+ metadata_content = json.dumps(metadata, ensure_ascii=False, indent=2)
183
+
184
+ # 創建臨時檔案並上傳
185
+ with open(f"temp_metadata_{timestamp}.json", "w", encoding="utf-8") as f:
186
+ f.write(metadata_content)
187
+
188
+ upload_file(
189
+ path_or_fileobj=f"temp_metadata_{timestamp}.json",
190
+ path_in_repo=metadata_path,
191
+ repo_id=OUTPUT_DATASET,
192
+ repo_type="dataset",
193
+ token=HF_TOKEN
194
+ )
195
+
196
+ # 刪除臨時檔案
197
+ os.remove(f"temp_metadata_{timestamp}.json")
198
+
199
+ return True, repo_path
200
+
201
+ except Exception as e:
202
+ print(f"❌ 上傳到 HF Dataset 失敗: {str(e)}")
203
+ return False, str(e)
204
+
205
+ # ==========================================
206
+ # 向量搜尋函數
207
  # ==========================================
208
  def average_pool(last_hidden_states, attention_mask):
209
  """Average pooling for embeddings"""
 
211
  return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
212
 
213
  def generate_query_embedding(query_text):
214
+ """生成查詢向量"""
215
  try:
 
216
  query_with_prefix = f"query: {query_text}"
217
 
 
218
  inputs = tokenizer(
219
  [query_with_prefix],
220
  max_length=512,
 
223
  return_tensors='pt'
224
  )
225
 
 
226
  with torch.no_grad():
227
  outputs = model(**inputs)
228
  query_embedding = average_pool(outputs.last_hidden_state, inputs['attention_mask'])
 
229
  query_embedding = torch.nn.functional.normalize(query_embedding, p=2, dim=1)
230
 
231
  return query_embedding.cpu().numpy()[0]
 
242
  你將收到一個查詢和幾個檢索到的訪談片段。你的任務是根據片段與查詢的相關性來評估和評分每個片段。
243
 
244
  評分指南:
245
+ - 1.0 = 完全相關
246
+ - 0.7-0.9 = 高度相關
247
+ - 0.5-0.7 = 中等相關
248
+ - 0.3-0.5 = 輕微相關
249
+ - 0-0.3 = 幾乎無關
 
 
 
 
 
 
 
 
250
 
251
+ 請為每個搜尋結果提供JSON格式的評分。"""
 
 
 
 
 
 
 
 
 
 
 
 
252
 
 
253
  results_text = f"查詢:{query}\n\n檢索結果:\n"
254
  for i, result in enumerate(search_results):
255
  results_text += f"\n結果 {i}:\n"
 
265
  return []
266
 
267
  try:
268
+ # Step 1: 向量檢索
269
  query_vector = generate_query_embedding(query)
270
  if query_vector is None:
271
  return []
 
273
  # Step 2: 計算相似度並過濾
274
  initial_results = []
275
  for i, item in enumerate(dataset):
276
+ # 排除採訪者
277
  if item['speaker'] in INTERVIEWERS:
278
  continue
279
 
280
+ # 嚴格的受訪者過濾
 
281
  if selected_speakers and len(selected_speakers) > 0:
282
  if item['speaker'] not in selected_speakers:
283
+ continue
284
 
285
  # 計算向量相似度
286
  item_vector = np.array(item['embedding'])
 
302
  if not candidates:
303
  return []
304
 
305
+ # Step 3: LLM 重排序(只對前10個)
 
 
306
  try:
307
+ rerank_prompt = build_reranking_prompt(query, candidates[:10])
308
+
309
  response = openai_client.chat.completions.create(
310
  model="gpt-4o-mini",
311
  messages=[
 
318
 
319
  rerank_results = json.loads(response.choices[0].message.content)
320
 
321
+ # Step 4: 加權計分
322
  final_results = []
323
  for i, candidate in enumerate(candidates[:10]):
324
+ llm_score = 0.5
325
 
 
326
  if 'results' in rerank_results:
327
  for r in rerank_results['results']:
328
  if r.get('index') == i:
329
  llm_score = r.get('relevance_score', 0.5)
330
  break
331
 
 
332
  weighted_score = 0.3 * candidate['vector_score'] + 0.7 * llm_score
333
 
334
  final_results.append(SearchResult(
 
341
  weighted_score=weighted_score
342
  ))
343
 
344
+ # 加入剩餘的候選
345
  for candidate in candidates[10:]:
346
  final_results.append(SearchResult(
347
  text=candidate['text'],
 
356
  # 按加權分數排序
357
  final_results.sort(key=lambda x: x.weighted_score, reverse=True)
358
 
359
+ # 只返回高於門檻的結果
360
+ filtered_results = [r for r in final_results if r.weighted_score >= RELEVANCE_THRESHOLD]
361
 
362
+ return filtered_results
363
 
364
  except Exception as e:
365
+ print(f"LLM 重排序失敗: {str(e)}")
366
+ # 降級處理
367
  return [SearchResult(
368
  text=c['text'],
369
  speaker=c['speaker'],
 
372
  vector_score=c['vector_score'],
373
  llm_score=0.0,
374
  weighted_score=c['vector_score']
375
+ ) for c in candidates if c['vector_score'] >= RELEVANCE_THRESHOLD]
376
 
377
  except Exception as e:
378
  print(f"智慧路由失敗: {str(e)}")
379
  return []
380
 
381
+ # ==========================================
382
+ # 並行處理與錯誤重試
383
+ # ==========================================
384
+ def call_gpt_with_retry(prompt, max_retries=MAX_RETRIES):
385
+ """調用 GPT 並實現錯誤重試機制"""
386
+ for attempt in range(max_retries):
387
+ try:
388
+ response = openai_client.chat.completions.create(
389
+ model="gpt-4o-mini",
390
+ messages=[
391
+ {"role": "system", "content": "你是訪談分析專家。基於提供的內容準確回答。"},
392
+ {"role": "user", "content": prompt}
393
+ ],
394
+ temperature=0.1,
395
+ timeout=30 # 30秒超時
396
+ )
397
+ return response.choices[0].message.content
398
+ except Exception as e:
399
+ if attempt < max_retries - 1:
400
+ wait_time = 2 ** attempt # 指數退避
401
+ print(f"API 調用失敗,{wait_time}秒後重試... (嘗試 {attempt + 1}/{max_retries})")
402
+ time.sleep(wait_time)
403
+ else:
404
+ print(f"API 調用最終失敗: {str(e)}")
405
+ return f"處理失敗: {str(e)}"
406
+
407
+ def process_single_question(question, selected_speakers, question_index=0, total_questions=1):
408
+ """處理單個問題(用於並行處理)"""
409
+ try:
410
+ # 更新狀態
411
+ with status_lock:
412
+ processing_status.current_item = f"問題 {question_index + 1}/{total_questions}"
413
+
414
+ # 使用智慧路由與重排序檢索
415
+ search_results = intelligent_routing_and_reranking(question, selected_speakers, top_k=30)
416
+
417
+ # 過濾結果
418
+ filtered_results = [r for r in search_results if r.weighted_score >= RELEVANCE_THRESHOLD]
419
+
420
+ if not filtered_results:
421
+ return {
422
+ 'question': question,
423
+ 'answer': "未找到相關內容",
424
+ 'raw_contexts': [],
425
+ 'success': False
426
+ }
427
+
428
+ # 構建上下文(使用所有符合條件的結果)
429
+ context = ""
430
+ raw_contexts = []
431
+
432
+ for j, result in enumerate(filtered_results):
433
+ context += f"[片段 {j+1}]\n"
434
+ context += f"發言人:{result.speaker}\n"
435
+ context += f"內容:{result.text}\n"
436
+ context += f"相關性:{result.weighted_score:.3f}\n\n"
437
+
438
+ raw_contexts.append({
439
+ 'speaker': result.speaker,
440
+ 'text': result.text,
441
+ 'turn_index': result.turn_index,
442
+ 'score': result.weighted_score
443
+ })
444
+
445
+ # 調用 GPT(含重試機制)
446
+ prompt = f"""基於以下訪談內容回答訪綱問題:
447
+
448
+ {context}
449
+
450
+ 問題:{question}
451
+
452
+ 請提供:
453
+ 1. 主要回答
454
+ 2. 不同受訪者的觀點(如果有)
455
+ 3. 具體引述"""
456
+
457
+ answer = call_gpt_with_retry(prompt)
458
+
459
+ return {
460
+ 'question': question,
461
+ 'answer': answer,
462
+ 'raw_contexts': raw_contexts,
463
+ 'success': True
464
+ }
465
+
466
+ except Exception as e:
467
+ print(f"處理問題失敗: {str(e)}")
468
+ return {
469
+ 'question': question,
470
+ 'answer': f"處理失敗: {str(e)}",
471
+ 'raw_contexts': [],
472
+ 'success': False
473
+ }
474
+
475
+ def parallel_process_questions(questions, selected_speakers, progress_callback=None):
476
+ """並行處理多個問題"""
477
+ results = []
478
+ total = len(questions)
479
 
480
+ with status_lock:
481
+ processing_status.total_items = total
482
+ processing_status.completed_items = 0
483
+ processing_status.failed_items = 0
484
+ processing_status.start_time = time.time()
485
 
486
+ with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
487
+ # 提交所有任務
488
+ future_to_question = {
489
+ executor.submit(
490
+ process_single_question,
491
+ question,
492
+ selected_speakers,
493
+ i,
494
+ total
495
+ ): (i, question)
496
+ for i, question in enumerate(questions)
497
+ }
498
+
499
+ # 處理完成的任務
500
+ for future in as_completed(future_to_question):
501
+ i, question = future_to_question[future]
502
+ try:
503
+ result = future.result(timeout=60) # 60秒超時
504
+ results.append((i, result))
505
+
506
+ with status_lock:
507
+ if result['success']:
508
+ processing_status.completed_items += 1
509
+ else:
510
+ processing_status.failed_items += 1
511
+
512
+ # 計算預估時間
513
+ elapsed = time.time() - processing_status.start_time
514
+ if processing_status.completed_items > 0:
515
+ avg_time = elapsed / processing_status.completed_items
516
+ remaining = total - processing_status.completed_items
517
+ processing_status.estimated_time = avg_time * remaining
518
+
519
+ # 進度回調
520
+ if progress_callback:
521
+ progress = (processing_status.completed_items + processing_status.failed_items) / total
522
+ progress_callback(progress, f"已處理 {processing_status.completed_items}/{total} 個問題")
523
+
524
+ except Exception as e:
525
+ print(f"任務執行失敗: {str(e)}")
526
+ results.append((i, {
527
+ 'question': question,
528
+ 'answer': f"處理失敗: {str(e)}",
529
+ 'raw_contexts': [],
530
+ 'success': False
531
+ }))
532
+
533
+ with status_lock:
534
+ processing_status.failed_items += 1
535
+ processing_status.errors.append(str(e))
536
 
537
+ # 按原始順序排序結果
538
+ results.sort(key=lambda x: x[0])
539
+ return [r[1] for r in results]
540
 
541
  # ==========================================
542
+ # RAG 對話函數
543
  # ==========================================
544
  def rag_chat(question, selected_speakers, history):
545
+ """RAG 對話處理"""
546
  if not init_success:
547
  return history + [[question, "系統尚未初始化,請稍後再試。"]]
548
 
549
  try:
550
  # 執行智慧路由與重排序
551
+ search_results = intelligent_routing_and_reranking(question, selected_speakers, top_k=30)
552
+
553
+ # 過濾結果(使用所有 >= 0.4 的結果)
554
+ filtered_results = [r for r in search_results if r.weighted_score >= RELEVANCE_THRESHOLD]
555
 
556
+ if not filtered_results:
557
  return history + [[question, "未找到相關內容,請嘗試其他問題。"]]
558
 
559
+ # 構建上下文(使用所有符合條件的結果)
560
  context = "相關訪談內容:\n\n"
561
  raw_contexts = []
562
 
563
+ for i, result in enumerate(filtered_results):
564
+ context += f"[片段 {i+1}]\n"
565
  context += f"發言人:{result.speaker}\n"
566
  context += f"內容:{result.text}\n"
567
+ context += f"相關性分數:{result.weighted_score:.3f}\n\n"
568
 
 
569
  if result.text:
570
  raw_context_text = f"[{result.speaker} - Turn {result.turn_index}]: {result.text}"
571
  raw_contexts.append(raw_context_text)
572
 
 
573
  if not raw_contexts:
574
  raw_contexts = ["未能提取原始內容"]
575
 
576
+ # 構建 GPT prompt
577
  prompt = f"""基於以下訪談內容回答問題。請提供準確、完整的回答。
578
 
579
  {context}
580
 
581
+ 問題:{question}"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
582
 
583
+ # 調用 GPT(含重試機制)
584
+ answer = call_gpt_with_retry(prompt)
585
 
586
+ # 添加原始 RAG 內容(完整顯示所有符合條件的)
587
+ answer_with_sources = f"{answer}\n\n---\n📚 **原始 RAG 來源(共 {len(raw_contexts)} 個):**\n"
588
+ for i, raw_context in enumerate(raw_contexts):
 
589
  if raw_context and raw_context != "未能提取原始內容":
590
+ answer_with_sources += f"\n**來源 {i+1}:**\n{raw_context}\n"
 
591
  else:
592
+ answer_with_sources += f"\n**來源 {i+1}:** 無內容\n"
593
 
594
  return history + [[question, answer_with_sources]]
595
 
596
  except Exception as e:
597
  return history + [[question, f"處理過程中發生錯誤:{str(e)}"]]
598
 
599
+ def export_chat_to_word(chat_history):
600
+ """將對話匯出為 Word 檔案"""
601
+ try:
602
+ doc = Document()
603
+ doc.add_heading('AI 對話記錄', 0)
604
+ doc.add_paragraph(f'匯出時間:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
605
+ doc.add_paragraph('')
606
+
607
+ for i, (question, answer) in enumerate(chat_history, 1):
608
+ doc.add_heading(f'對話 {i}', level=1)
609
+
610
+ doc.add_heading('問題:', level=2)
611
+ doc.add_paragraph(question)
612
+
613
+ doc.add_heading('回答:', level=2)
614
+ for line in answer.split('\n'):
615
+ if line.strip():
616
+ doc.add_paragraph(line)
617
+
618
+ doc.add_page_break()
619
+
620
+ # 保存到記憶體
621
+ output_buffer = io.BytesIO()
622
+ doc.save(output_buffer)
623
+ output_buffer.seek(0)
624
+
625
+ # 保存到檔案
626
+ output_filename = f"chat_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
627
+ with open(output_filename, 'wb') as f:
628
+ f.write(output_buffer.getvalue())
629
+
630
+ # 上傳到 HF Dataset
631
+ upload_to_hf_dataset(output_filename, file_type="chat", metadata={
632
+ 'export_time': datetime.now().isoformat(),
633
+ 'total_conversations': len(chat_history)
634
+ })
635
+
636
+ return output_filename, "對話已匯出並上傳到資料集"
637
+
638
+ except Exception as e:
639
+ return None, f"匯出失敗:{str(e)}"
640
+
641
  # ==========================================
642
+ # 訪綱填答函數
643
  # ==========================================
644
  def parse_word_document(file_path):
645
  """解析 Word 文檔中的問題"""
 
667
  base_name = os.path.basename(filename)
668
  base_name_no_ext = os.path.splitext(base_name)[0]
669
 
 
670
  for speaker in available_speakers:
671
  if speaker in base_name_no_ext:
672
  return [speaker]
673
 
674
+ return None
675
 
676
+ def single_interviewee_guide_filling(file_path, selected_speakers, file_name=None, progress_callback=None):
677
+ """單一受訪者訪綱填答 - 使用並行處理"""
678
  if not init_success:
679
  return None, "系統尚未初始化"
680
 
681
  try:
682
+ # 從檔名檢測受訪者
683
  if file_name:
684
  detected_speakers = extract_speaker_from_filename(file_name, all_speakers)
685
  if detected_speakers:
 
692
  if not questions:
693
  return None, "未能從文檔中提取問題"
694
 
695
+ # 進度更新
696
+ if progress_callback:
697
+ progress_callback(0.1, f"開始處理 {len(questions)} 個問題...")
698
+
699
+ # 並行處理所有問題
700
+ print(f"開始並行處理 {len(questions)} 個問題")
701
+ results = parallel_process_questions(questions, selected_speakers, progress_callback)
702
+
703
  # 創建新的 Word 文檔
704
  output_doc = Document()
705
  output_doc.add_heading('訪談訪綱 - AI 智慧填答', 0)
706
  output_doc.add_paragraph(f'處理時間:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
707
  output_doc.add_paragraph(f'原始檔案:{file_name if file_name else "未知"}')
708
  output_doc.add_paragraph(f'選擇的受訪者:{", ".join(selected_speakers) if selected_speakers else "全部"}')
709
+ output_doc.add_paragraph(f'使用技術:並行處理 ({MAX_WORKERS} 組) + 冠軍級 RAG')
710
+ output_doc.add_paragraph(f'處理統計:成功 {processing_status.completed_items}/{processing_status.total_items},失敗 {processing_status.failed_items}')
711
  output_doc.add_paragraph('')
712
 
713
+ # 添加處理結果
714
+ for i, result in enumerate(results, 1):
715
  output_doc.add_heading(f'問題 {i}', level=1)
716
+ output_doc.add_paragraph(result['question'])
 
 
 
 
 
 
717
 
718
+ if result['success'] and result['raw_contexts']:
719
+ # AI 回答
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
720
  output_doc.add_heading('AI 分析回答:', level=2)
721
+ for line in result['answer'].split('\n'):
722
  if line.strip():
723
  output_doc.add_paragraph(line)
724
 
725
+ # 原始 RAG 內容(顯示所有符合條件的)
726
+ output_doc.add_heading(f'原始 RAG 向量檢索內容(共 {len(result["raw_contexts"])} 個):', level=2)
727
+ for j, raw in enumerate(result['raw_contexts']):
728
  p = output_doc.add_paragraph()
729
+ p.add_run(f"{j+1}. [{raw['speaker']} - Turn {raw['turn_index']}] ").bold = True
730
  p.add_run(f"(相關性: {raw['score']:.3f})\n")
731
+ p.add_run(raw['text']) # 完整顯示
 
732
  else:
733
+ output_doc.add_paragraph(result['answer'])
734
 
735
+ output_doc.add_page_break()
 
 
 
 
 
736
 
737
  # 保存文檔
738
  output_buffer = io.BytesIO()
 
746
  with open(output_filename, 'wb') as f:
747
  f.write(output_buffer.getvalue())
748
 
749
+ # 自動上傳到 HF Dataset
750
+ if progress_callback:
751
+ progress_callback(0.9, "正在上傳到資料集...")
752
+
753
+ success, path = upload_to_hf_dataset(output_filename, file_type="guide", metadata={
754
+ 'original_file': file_name,
755
+ 'speakers': selected_speakers,
756
+ 'total_questions': len(questions),
757
+ 'successful_answers': processing_status.completed_items,
758
+ 'processing_time': time.time() - processing_status.start_time
759
+ })
760
+
761
+ if success:
762
+ message = f"訪綱填答完成!已上傳到:{path}"
763
+ else:
764
+ message = f"訪綱填答完成!本地檔案:{output_filename}"
765
+
766
+ if progress_callback:
767
+ progress_callback(1.0, message)
768
+
769
+ return output_filename, message
770
 
771
  except Exception as e:
772
  return None, f"處理失敗:{str(e)}"
773
 
774
+ def batch_process_guides(files, default_speakers, progress_callback=None):
775
+ """批量處理多個訪綱檔案(並行處理)"""
776
  if not init_success:
777
  return [], "系統尚未初始化"
778
 
779
  results = []
780
  processed_files = []
781
+ total_files = len(files)
782
 
783
  try:
 
784
  print(f"開始批量處理 {total_files} 個檔案")
785
 
786
+ # 重置狀態
787
+ with status_lock:
788
+ processing_status.total_items = total_files
789
+ processing_status.completed_items = 0
790
+ processing_status.failed_items = 0
791
+ processing_status.errors.clear()
792
+
793
+ def process_file(file_info):
794
+ """處理單個檔案的函數"""
795
+ idx, file = file_info
796
  try:
797
  file_name = file.name if hasattr(file, 'name') else str(file)
798
+ print(f"\n處理檔案 {idx+1}/{total_files}: {file_name}")
799
 
800
+ # 從檔名檢測受訪者
801
  detected_speakers = extract_speaker_from_filename(file_name, all_speakers)
802
 
803
  if detected_speakers:
804
  speakers_to_use = detected_speakers
805
+ status_msg = f"檔案 {idx+1}: 檢測到受訪者 {detected_speakers[0]}"
806
  else:
807
  speakers_to_use = default_speakers
808
+ status_msg = f"檔案 {idx+1}: 使用預設受訪者"
809
 
810
  print(status_msg)
 
811
 
812
+ # 處理單個檔案(含並行處理問題)
813
  output_file, process_status = single_interviewee_guide_filling(
814
  file.name if hasattr(file, 'name') else file,
815
  speakers_to_use,
816
+ file_name,
817
+ None # 批量處理時不使用個別進度回調
818
  )
819
 
820
  if output_file:
821
+ return {
822
+ 'success': True,
823
+ 'file_name': file_name,
824
+ 'output_file': output_file,
825
+ 'status': process_status
826
+ }
827
  else:
828
+ return {
829
+ 'success': False,
830
+ 'file_name': file_name,
831
+ 'error': process_status
832
+ }
833
+
834
  except Exception as e:
835
+ return {
836
+ 'success': False,
837
+ 'file_name': file_name if 'file_name' in locals() else f"檔案 {idx+1}",
838
+ 'error': str(e)
839
+ }
840
+
841
+ # 使用執行緒池並行處理多個檔案
842
+ with ThreadPoolExecutor(max_workers=min(MAX_WORKERS, total_files)) as executor:
843
+ # 提交所有檔案處理任務
844
+ future_to_file = {
845
+ executor.submit(process_file, (i, file)): i
846
+ for i, file in enumerate(files)
847
+ }
848
+
849
+ # 處理完成的任務
850
+ for future in as_completed(future_to_file):
851
+ file_idx = future_to_file[future]
852
+ try:
853
+ result = future.result(timeout=300) # 5分鐘超時
854
+
855
+ if result['success']:
856
+ processed_files.append(result['output_file'])
857
+ results.append(f"✅ {result['file_name']} -> {result['output_file']}")
858
+
859
+ with status_lock:
860
+ processing_status.completed_items += 1
861
+ else:
862
+ results.append(f"❌ {result['file_name']}: {result['error']}")
863
+
864
+ with status_lock:
865
+ processing_status.failed_items += 1
866
+ processing_status.errors.append(result['error'])
867
+
868
+ # 更新進度
869
+ if progress_callback:
870
+ progress = (processing_status.completed_items + processing_status.failed_items) / total_files
871
+ progress_callback(
872
+ progress,
873
+ f"已處理 {processing_status.completed_items + processing_status.failed_items}/{total_files} 個檔案"
874
+ )
875
+
876
+ except Exception as e:
877
+ error_msg = f"檔案 {file_idx+1} 處理超時或失敗: {str(e)}"
878
+ print(error_msg)
879
+ results.append(error_msg)
880
+
881
+ with status_lock:
882
+ processing_status.failed_items += 1
883
+ processing_status.errors.append(str(e))
884
 
885
  # 彙總結果
886
+ summary = f"\n處理完成!\n成功: {processing_status.completed_items}/{total_files} 個檔案\n"
887
+ if processing_status.failed_items > 0:
888
+ summary += f"失敗: {processing_status.failed_items} 個檔案\n"
889
  summary += "\n詳細結果:\n" + "\n".join(results)
890
 
891
  return processed_files, summary
 
906
  .gradio-container {
907
  font-family: 'Microsoft JhengHei', sans-serif;
908
  }
909
+ .progress-bar {
910
+ background-color: #4CAF50;
911
  }
912
  """
913
  ) as app:
914
  # 標題
915
  gr.Markdown("""
916
+ # 🎙️ 訪談轉錄稿智慧分析系統 v2.0
917
 
918
+ **技術架構:** Multilingual-E5-Large + GPT-4o-mini + 冠軍級 RAG + 並行處理
919
 
920
  **核心功能:**
921
+ - 🔍 智慧語義搜尋(顯示所有 ≥0.4 分結果)
922
+ - 💬 AI 對話(含匯出功能)
923
+ - 📝 訪綱自動填答(5組並行處理)
924
+ - 📊 批量處理(自動上傳 HF Dataset
925
+ - ⚡ 錯誤重試機制 + 進度追蹤
926
  """)
927
 
928
  # 系統狀態
 
938
  with gr.Tabs():
939
  # Tab 1: AI 對話
940
  with gr.Tab("💬 AI 對話"):
941
+ gr.Markdown("### 智慧問答系統(顯示所有相關 RAG)")
942
 
943
  with gr.Row():
944
  with gr.Column(scale=1):
 
966
 
967
  with gr.Row():
968
  clear_btn = gr.Button("清除對話")
969
+ export_btn = gr.Button("📥 匯出對話為 Word", variant="secondary")
970
+
971
+ export_status = gr.Textbox(
972
+ label="匯出狀態",
973
+ visible=False
974
+ )
975
+
976
+ export_file = gr.File(
977
+ label="下載匯出檔案",
978
+ visible=False
979
+ )
980
 
981
  # Tab 2: 訪綱填答
982
  with gr.Tab("📝 訪綱填答"):
 
984
  ### 智慧訪綱填答系統
985
 
986
  **特色功能:**
987
+ - 🚀 5組並行處理(速度提升5倍)
988
+ - 📊 顯示所有 ≥0.4 分的 RAG 結果
989
+ - 🔄 錯誤自動重試(最多3次)
990
+ - 📤 自動上傳到 HF Dataset
991
+ - 🏷️ 檔名自動識別受訪者
 
 
 
 
992
  """)
993
 
994
  with gr.Row():
 
999
  info="檔名中有受訪者名稱時會自動覆蓋此選擇"
1000
  )
1001
 
1002
+ # 單檔上傳
1003
  with gr.Accordion("單檔處理", open=False):
1004
  single_file_input = gr.File(
1005
  label="上傳單個訪綱 (Word 格式)",
 
1007
  )
1008
  single_process_btn = gr.Button("處理單檔", variant="secondary")
1009
 
1010
+ # 批量上傳
1011
  batch_file_input = gr.File(
1012
  label="批量上傳訪綱(最多15個 Word 檔案)",
1013
  file_types=[".docx"],
1014
  file_count="multiple"
1015
  )
1016
 
1017
+ batch_process_btn = gr.Button("🚀 批量並行處理", variant="primary", size="lg")
1018
 
1019
  with gr.Column():
1020
+ # 進度條
1021
+ progress_bar = gr.Progress()
1022
+
1023
  process_status = gr.Textbox(
1024
  label="處理狀態",
1025
  interactive=False,
1026
  lines=10
1027
  )
1028
 
1029
+ # 處理統計
1030
+ with gr.Row():
1031
+ stat_total = gr.Number(label="總計", value=0)
1032
+ stat_success = gr.Number(label="成功", value=0)
1033
+ stat_failed = gr.Number(label="失敗", value=0)
1034
+ stat_time = gr.Number(label="預估時間(秒)", value=0)
1035
+
1036
+ # 下載區
1037
  single_download_file = gr.File(
1038
  label="下載單檔結果",
1039
  visible=False
1040
  )
1041
 
 
1042
  batch_download_files = gr.File(
1043
  label="下載所有結果",
1044
  visible=False,
 
1048
  # 技術細節
1049
  with gr.Accordion("🔧 技術細節", open=False):
1050
  gr.Markdown("""
1051
+ ### 系統特色
1052
+
1053
+ **1. 並行處理架構**
1054
+ - 5組同時處理不同問題
1055
+ - ThreadPoolExecutor 管理
1056
+ - 自動負載平衡
1057
+
1058
+ **2. RAG 結果顯示**
1059
+ - 所有 weighted_score ≥ 0.4 的結果都納入分析
1060
+ - 完整顯示原始內容(不截斷)
1061
+ - 顯示相關性分數
1062
+
1063
+ **3. 錯誤處理**
1064
+ - API 調用失敗自動重試(最多3次)
1065
+ - 指數退避策略(2^n 秒)
1066
+ - 失敗隔離(不影響其他任務)
1067
+
1068
+ **4. HF Dataset 自動上傳**
1069
+ - 位置:s880453/interview-outputs
1070
+ - 自動分類:guide_outputs / chat_exports
1071
+ - 包含處理 metadata
1072
+
1073
+ **5. 進度追蹤**
1074
+ - 即時顯示處理進度
1075
+ - 預估剩餘時間
1076
+ - 詳細錯誤日誌
1077
  """)
1078
 
1079
  # 事件處理
 
1086
  def clear_chat():
1087
  return []
1088
 
1089
+ def export_chat(history):
1090
+ if not history:
1091
+ return gr.Textbox(value="沒有對話可匯出", visible=True), gr.File(visible=False)
1092
+
1093
+ file_path, status = export_chat_to_word(history)
1094
+ if file_path:
1095
+ return (
1096
+ gr.Textbox(value=status, visible=True),
1097
+ gr.File(value=file_path, visible=True)
1098
+ )
1099
+ else:
1100
+ return gr.Textbox(value=status, visible=True), gr.File(visible=False)
1101
+
1102
+ def process_single_guide_with_progress(file, speakers):
1103
+ """處理單個檔案(含進度顯示)"""
1104
  if not file:
1105
+ return (
1106
+ "請上傳文件",
1107
+ gr.File(visible=False),
1108
+ 0, 0, 0, 0
1109
+ )
1110
 
1111
+ def progress_update(progress, message):
1112
+ return message
1113
+
1114
+ result_file, status = single_interviewee_guide_filling(
1115
+ file.name,
1116
+ speakers,
1117
+ file.name,
1118
+ progress_update
1119
+ )
1120
 
1121
  if result_file:
1122
+ return (
1123
+ status,
1124
+ gr.File(value=result_file, visible=True),
1125
+ processing_status.total_items,
1126
+ processing_status.completed_items,
1127
+ processing_status.failed_items,
1128
+ processing_status.estimated_time
1129
+ )
1130
  else:
1131
+ return (
1132
+ status,
1133
+ gr.File(visible=False),
1134
+ processing_status.total_items,
1135
+ processing_status.completed_items,
1136
+ processing_status.failed_items,
1137
+ 0
1138
+ )
1139
 
1140
+ def process_batch_guides_with_progress(files, speakers):
1141
+ """批量處理(含進度顯示)"""
1142
  if not files:
1143
+ return (
1144
+ "請上傳至少一個檔案",
1145
+ gr.File(visible=False),
1146
+ 0, 0, 0, 0
1147
+ )
1148
 
 
1149
  if len(files) > 15:
1150
+ return (
1151
+ f"檔案數量超過限制(最多15個),您上傳了 {len(files)} 個",
1152
+ gr.File(visible=False),
1153
+ 0, 0, 0, 0
1154
+ )
1155
+
1156
+ def progress_update(progress, message):
1157
+ return message
1158
 
1159
  # 批量處理
1160
+ processed_files, status = batch_process_guides(files, speakers, progress_update)
1161
 
1162
  if processed_files:
1163
+ return (
1164
+ status,
1165
+ gr.File(value=processed_files, visible=True, file_count="multiple"),
1166
+ processing_status.total_items,
1167
+ processing_status.completed_items,
1168
+ processing_status.failed_items,
1169
+ processing_status.estimated_time
1170
+ )
1171
  else:
1172
+ return (
1173
+ status,
1174
+ gr.File(visible=False),
1175
+ processing_status.total_items,
1176
+ processing_status.completed_items,
1177
+ processing_status.failed_items,
1178
+ 0
1179
+ )
1180
 
1181
  def update_status():
1182
  success, message = initialize_system()
 
1203
 
1204
  clear_btn.click(clear_chat, outputs=[chatbot])
1205
 
1206
+ export_btn.click(
1207
+ export_chat,
1208
+ inputs=[chatbot],
1209
+ outputs=[export_status, export_file]
1210
+ )
1211
+
1212
  # 單檔處理
1213
  single_process_btn.click(
1214
+ process_single_guide_with_progress,
1215
  inputs=[single_file_input, guide_speakers],
1216
+ outputs=[
1217
+ process_status,
1218
+ single_download_file,
1219
+ stat_total,
1220
+ stat_success,
1221
+ stat_failed,
1222
+ stat_time
1223
+ ]
1224
  )
1225
 
1226
  # 批量處理
1227
  batch_process_btn.click(
1228
+ process_batch_guides_with_progress,
1229
  inputs=[batch_file_input, guide_speakers],
1230
+ outputs=[
1231
+ process_status,
1232
+ batch_download_files,
1233
+ stat_total,
1234
+ stat_success,
1235
+ stat_failed,
1236
+ stat_time
1237
+ ]
1238
  )
1239
 
1240
  init_btn.click(
 
1247
  update_status,
1248
  outputs=[status_text, speaker_selector, guide_speakers]
1249
  )
1250
+
1251
+ # 啟用 Queue(支援並行處理)
1252
+ app.queue(
1253
+ concurrency_count=MAX_WORKERS,
1254
+ max_size=50
1255
+ )
1256
 
1257
  return app
1258
 
 
1260
  # 主程式入口
1261
  # ==========================================
1262
  if __name__ == "__main__":
1263
+ # 創建並啟動應用(加入密碼保護)
1264
  app = create_interface()
1265
+
1266
+ # 設定身份驗證
1267
+ # 支援多種驗證方式:
1268
+ # 1. 任意使用者名稱 + 正確密碼
1269
+ # 2. 可以設定多組帳號密碼
1270
+ def authenticate(username, password):
1271
+ """驗證函數 - 確保安全性"""
1272
+ # 主要密碼驗證
1273
+ if password == ACCESS_PASSWORD:
1274
+ return True
1275
+ # 可選:添加特定使用者帳號
1276
+ valid_users = {
1277
+ "admin": ACCESS_PASSWORD,
1278
+ "user": ACCESS_PASSWORD
1279
+ }
1280
+ return username in valid_users and valid_users[username] == password
1281
+
1282
+ # 啟動應用(需要密碼才能訪問)
1283
+ app.launch(
1284
+ share=False,
1285
+ server_name="0.0.0.0",
1286
+ server_port=7860,
1287
+ auth=authenticate,
1288
+ auth_message="🔒 訪談轉錄稿 RAG 系統\n請輸入密碼以訪問系統",
1289
+ show_api=False, # 隱藏 API 文檔
1290
+ show_error=False # 不顯示詳細錯誤(增加安全性)
1291
+ )