Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -12,6 +12,8 @@ from openai import OpenAI
|
|
| 12 |
from docx import Document
|
| 13 |
import io
|
| 14 |
from typing import List, Dict, Any, Optional, Tuple
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# ==========================================
|
| 17 |
# 環境變數設定
|
|
@@ -26,6 +28,40 @@ EMBEDDING_MODEL = "intfloat/multilingual-e5-large"
|
|
| 26 |
# 採訪者名單(需要排除)
|
| 27 |
INTERVIEWERS = ["徐美苓", "許弘諺", "郭禹彤"]
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
# ==========================================
|
| 30 |
# 全域變數
|
| 31 |
# ==========================================
|
|
@@ -68,7 +104,6 @@ def initialize_system():
|
|
| 68 |
print(f"🤖 正在載入模型: {EMBEDDING_MODEL}")
|
| 69 |
tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL)
|
| 70 |
model = AutoModel.from_pretrained(EMBEDDING_MODEL)
|
| 71 |
-
# 設為評估模式
|
| 72 |
model.eval()
|
| 73 |
print("✅ 嵌入模型載入成功")
|
| 74 |
|
|
@@ -91,7 +126,7 @@ def initialize_system():
|
|
| 91 |
return False, error_msg
|
| 92 |
|
| 93 |
# ==========================================
|
| 94 |
-
#
|
| 95 |
# ==========================================
|
| 96 |
def average_pool(last_hidden_states, attention_mask):
|
| 97 |
"""Average pooling for embeddings"""
|
|
@@ -99,9 +134,9 @@ def average_pool(last_hidden_states, attention_mask):
|
|
| 99 |
return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
|
| 100 |
|
| 101 |
def generate_query_embedding(query_text):
|
| 102 |
-
"""生成查詢向量"""
|
| 103 |
try:
|
| 104 |
-
#
|
| 105 |
query_with_prefix = f"query: {query_text}"
|
| 106 |
|
| 107 |
# Tokenize
|
|
@@ -117,6 +152,7 @@ def generate_query_embedding(query_text):
|
|
| 117 |
with torch.no_grad():
|
| 118 |
outputs = model(**inputs)
|
| 119 |
query_embedding = average_pool(outputs.last_hidden_state, inputs['attention_mask'])
|
|
|
|
| 120 |
query_embedding = torch.nn.functional.normalize(query_embedding, p=2, dim=1)
|
| 121 |
|
| 122 |
return query_embedding.cpu().numpy()[0]
|
|
@@ -124,106 +160,271 @@ def generate_query_embedding(query_text):
|
|
| 124 |
print(f"生成查詢向量失敗: {str(e)}")
|
| 125 |
return None
|
| 126 |
|
| 127 |
-
|
| 128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
if not dataset or not init_success:
|
| 130 |
return []
|
| 131 |
|
| 132 |
try:
|
| 133 |
-
#
|
| 134 |
query_vector = generate_query_embedding(query)
|
| 135 |
if query_vector is None:
|
| 136 |
return []
|
| 137 |
|
| 138 |
-
#
|
| 139 |
-
|
| 140 |
for i, item in enumerate(dataset):
|
| 141 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
if selected_speakers and item['speaker'] not in selected_speakers:
|
| 143 |
continue
|
| 144 |
|
| 145 |
-
#
|
| 146 |
item_vector = np.array(item['embedding'])
|
| 147 |
-
|
| 148 |
|
| 149 |
-
|
| 150 |
-
'
|
| 151 |
'text': item.get('text', ''),
|
| 152 |
'speaker': item.get('speaker', ''),
|
| 153 |
'turn_index': item.get('turn_index', 0),
|
| 154 |
-
'file_id': item.get('file_id', '')
|
|
|
|
| 155 |
})
|
| 156 |
|
| 157 |
-
#
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
except Exception as e:
|
| 161 |
-
print(f"
|
| 162 |
return []
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
"""調用 GPT-4o-mini"""
|
| 169 |
-
if not openai_client:
|
| 170 |
-
return "OpenAI 客戶端未初始化"
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
# ==========================================
|
| 186 |
-
# RAG
|
| 187 |
# ==========================================
|
| 188 |
def rag_chat(question, selected_speakers, history):
|
| 189 |
-
"""RAG 對話處理"""
|
| 190 |
if not init_success:
|
| 191 |
return history + [[question, "系統尚未初始化,請稍後再試。"]]
|
| 192 |
|
| 193 |
try:
|
| 194 |
-
#
|
| 195 |
-
search_results =
|
| 196 |
|
| 197 |
if not search_results:
|
| 198 |
return history + [[question, "未找到相關內容,請嘗試其他問題。"]]
|
| 199 |
|
| 200 |
-
#
|
| 201 |
context = "相關訪談內容:\n\n"
|
| 202 |
-
|
|
|
|
|
|
|
| 203 |
context += f"[片段 {i}]\n"
|
| 204 |
-
context += f"發言人:{result
|
| 205 |
-
context += f"內容:{result
|
| 206 |
-
context += f"
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
-
# 構建 GPT prompt
|
| 209 |
-
prompt = f"""
|
| 210 |
|
| 211 |
{context}
|
| 212 |
|
| 213 |
問題:{question}
|
| 214 |
|
| 215 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
-
#
|
| 218 |
-
|
|
|
|
|
|
|
| 219 |
|
| 220 |
-
return history + [[question,
|
| 221 |
|
| 222 |
except Exception as e:
|
| 223 |
return history + [[question, f"處理過程中發生錯誤:{str(e)}"]]
|
| 224 |
|
| 225 |
# ==========================================
|
| 226 |
-
#
|
| 227 |
# ==========================================
|
| 228 |
def parse_word_document(file_path):
|
| 229 |
"""解析 Word 文檔中的問題"""
|
|
@@ -233,10 +434,9 @@ def parse_word_document(file_path):
|
|
| 233 |
|
| 234 |
for para in doc.paragraphs:
|
| 235 |
text = para.text.strip()
|
| 236 |
-
# 識別問題
|
| 237 |
if text and (
|
| 238 |
any(char in text for char in ['?', '?']) or
|
| 239 |
-
text[0].isdigit() or
|
| 240 |
text.startswith(('Q', '問'))
|
| 241 |
):
|
| 242 |
questions.append(text)
|
|
@@ -246,72 +446,108 @@ def parse_word_document(file_path):
|
|
| 246 |
print(f"解析文檔失敗: {str(e)}")
|
| 247 |
return []
|
| 248 |
|
| 249 |
-
def
|
| 250 |
-
"""
|
| 251 |
if not init_success:
|
| 252 |
return None, "系統尚未初始化"
|
| 253 |
|
| 254 |
try:
|
| 255 |
-
# 解析 Word
|
| 256 |
questions = parse_word_document(file_path)
|
| 257 |
|
| 258 |
if not questions:
|
| 259 |
-
return None, "
|
| 260 |
|
| 261 |
# 創建新的 Word 文檔
|
| 262 |
output_doc = Document()
|
| 263 |
-
output_doc.add_heading('訪談訪綱 - AI
|
| 264 |
output_doc.add_paragraph(f'處理時間:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
|
| 265 |
output_doc.add_paragraph(f'選擇的受訪者:{", ".join(selected_speakers) if selected_speakers else "全部"}')
|
|
|
|
| 266 |
output_doc.add_paragraph('')
|
| 267 |
|
| 268 |
-
#
|
| 269 |
-
for i, question in enumerate(questions[:10], 1):
|
| 270 |
-
|
| 271 |
-
output_doc.add_heading(f'問題 {i}', level=2)
|
| 272 |
output_doc.add_paragraph(question)
|
| 273 |
|
| 274 |
-
#
|
| 275 |
-
search_results =
|
| 276 |
|
| 277 |
if search_results:
|
| 278 |
# 構建上下文
|
| 279 |
context = ""
|
| 280 |
-
|
| 281 |
-
context += f"發言人:{result['speaker']}\n"
|
| 282 |
-
context += f"內容:{result['text'][:300]}\n\n"
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
{context}
|
| 288 |
|
| 289 |
問題:{question}
|
| 290 |
|
| 291 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
-
answer =
|
| 294 |
|
| 295 |
-
#
|
| 296 |
-
output_doc.add_heading('
|
| 297 |
-
|
|
|
|
|
|
|
| 298 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
else:
|
| 300 |
output_doc.add_paragraph("未找到相關內容")
|
| 301 |
|
| 302 |
-
output_doc.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
|
| 304 |
# 保存文檔
|
| 305 |
output_buffer = io.BytesIO()
|
| 306 |
output_doc.save(output_buffer)
|
| 307 |
output_buffer.seek(0)
|
| 308 |
|
| 309 |
-
# 保存到檔案
|
| 310 |
output_filename = f"filled_guide_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
|
| 311 |
with open(output_filename, 'wb') as f:
|
| 312 |
f.write(output_buffer.getvalue())
|
| 313 |
|
| 314 |
-
return output_filename, "
|
| 315 |
|
| 316 |
except Exception as e:
|
| 317 |
return None, f"處理失敗:{str(e)}"
|
|
@@ -322,12 +558,29 @@ def fill_interview_guide(file_path, selected_speakers):
|
|
| 322 |
def create_interface():
|
| 323 |
"""創建 Gradio 介面"""
|
| 324 |
|
| 325 |
-
with gr.Blocks(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
# 標題
|
| 327 |
gr.Markdown("""
|
| 328 |
# 🎙️ 訪談轉錄稿智慧分析系統
|
| 329 |
|
| 330 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
""")
|
| 332 |
|
| 333 |
# 系統狀態
|
|
@@ -343,6 +596,8 @@ def create_interface():
|
|
| 343 |
with gr.Tabs():
|
| 344 |
# Tab 1: AI 對話
|
| 345 |
with gr.Tab("💬 AI 對話"):
|
|
|
|
|
|
|
| 346 |
with gr.Row():
|
| 347 |
with gr.Column(scale=1):
|
| 348 |
gr.Markdown("### 選擇受訪者")
|
|
@@ -355,7 +610,8 @@ def create_interface():
|
|
| 355 |
with gr.Column(scale=3):
|
| 356 |
chatbot = gr.Chatbot(
|
| 357 |
height=500,
|
| 358 |
-
label="對話記錄"
|
|
|
|
| 359 |
)
|
| 360 |
|
| 361 |
with gr.Row():
|
|
@@ -366,16 +622,20 @@ def create_interface():
|
|
| 366 |
)
|
| 367 |
send_btn = gr.Button("發送", variant="primary", scale=1)
|
| 368 |
|
| 369 |
-
|
|
|
|
|
|
|
| 370 |
|
| 371 |
# Tab 2: 訪綱填答
|
| 372 |
with gr.Tab("📝 訪綱填答"):
|
| 373 |
gr.Markdown("""
|
| 374 |
-
###
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
|
|
|
|
|
|
| 379 |
""")
|
| 380 |
|
| 381 |
with gr.Row():
|
|
@@ -383,7 +643,7 @@ def create_interface():
|
|
| 383 |
guide_speakers = gr.CheckboxGroup(
|
| 384 |
choices=[],
|
| 385 |
label="選擇受訪者",
|
| 386 |
-
info="
|
| 387 |
)
|
| 388 |
|
| 389 |
file_input = gr.File(
|
|
@@ -404,14 +664,26 @@ def create_interface():
|
|
| 404 |
visible=False
|
| 405 |
)
|
| 406 |
|
| 407 |
-
#
|
| 408 |
-
with gr.Accordion("
|
| 409 |
gr.Markdown("""
|
| 410 |
-
###
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
-
|
| 414 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
""")
|
| 416 |
|
| 417 |
# 事件處理
|
|
@@ -428,7 +700,7 @@ def create_interface():
|
|
| 428 |
if not file:
|
| 429 |
return "請上傳文件", gr.File(visible=False)
|
| 430 |
|
| 431 |
-
result_file, status =
|
| 432 |
|
| 433 |
if result_file:
|
| 434 |
return status, gr.File(value=result_file, visible=True)
|
|
@@ -438,7 +710,6 @@ def create_interface():
|
|
| 438 |
def update_status():
|
| 439 |
success, message = initialize_system()
|
| 440 |
if success:
|
| 441 |
-
# 更新發言人列表
|
| 442 |
return (
|
| 443 |
message,
|
| 444 |
gr.CheckboxGroup(choices=all_speakers),
|
|
|
|
| 12 |
from docx import Document
|
| 13 |
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 |
# 環境變數設定
|
|
|
|
| 28 |
# 採訪者名單(需要排除)
|
| 29 |
INTERVIEWERS = ["徐美苓", "許弘諺", "郭禹彤"]
|
| 30 |
|
| 31 |
+
# ==========================================
|
| 32 |
+
# 結構化數據模型(Pydantic 風格)
|
| 33 |
+
# ==========================================
|
| 34 |
+
@dataclass
|
| 35 |
+
class SearchResult:
|
| 36 |
+
"""搜尋結果結構"""
|
| 37 |
+
text: str
|
| 38 |
+
speaker: str
|
| 39 |
+
turn_index: int
|
| 40 |
+
file_id: str
|
| 41 |
+
vector_score: float = 0.0
|
| 42 |
+
llm_score: float = 0.0
|
| 43 |
+
weighted_score: float = 0.0
|
| 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 |
# 全域變數
|
| 67 |
# ==========================================
|
|
|
|
| 104 |
print(f"🤖 正在載入模型: {EMBEDDING_MODEL}")
|
| 105 |
tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL)
|
| 106 |
model = AutoModel.from_pretrained(EMBEDDING_MODEL)
|
|
|
|
| 107 |
model.eval()
|
| 108 |
print("✅ 嵌入模型載入成功")
|
| 109 |
|
|
|
|
| 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 |
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
|
|
|
|
| 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]
|
|
|
|
| 160 |
print(f"生成查詢向量失敗: {str(e)}")
|
| 161 |
return None
|
| 162 |
|
| 163 |
+
# ==========================================
|
| 164 |
+
# 冠軍級智慧路由與重排序系統
|
| 165 |
+
# ==========================================
|
| 166 |
+
def build_reranking_prompt(query: str, search_results: List[Dict]) -> str:
|
| 167 |
+
"""構建重排序的結構化 Prompt"""
|
| 168 |
+
instruction = """你是一個訪談內容檢索排序系統。
|
| 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"
|
| 204 |
+
results_text += f"發言人:{result['speaker']}\n"
|
| 205 |
+
results_text += f"內容:{result['text'][:500]}\n"
|
| 206 |
+
results_text += f"Turn Index:{result['turn_index']}\n"
|
| 207 |
+
|
| 208 |
+
return f"{instruction}\n\n{results_text}"
|
| 209 |
+
|
| 210 |
+
def intelligent_routing_and_reranking(query: str, selected_speakers: List[str], top_k: int = 30) -> List[SearchResult]:
|
| 211 |
+
"""智慧路由與重排序 - 冠軍策���實現"""
|
| 212 |
if not dataset or not init_success:
|
| 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 []
|
| 220 |
|
| 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 |
if selected_speakers and item['speaker'] not in selected_speakers:
|
| 230 |
continue
|
| 231 |
|
| 232 |
+
# 計算向量相似度
|
| 233 |
item_vector = np.array(item['embedding'])
|
| 234 |
+
vector_score = float(np.dot(query_vector, item_vector))
|
| 235 |
|
| 236 |
+
initial_results.append({
|
| 237 |
+
'index': i,
|
| 238 |
'text': item.get('text', ''),
|
| 239 |
'speaker': item.get('speaker', ''),
|
| 240 |
'turn_index': item.get('turn_index', 0),
|
| 241 |
+
'file_id': item.get('file_id', ''),
|
| 242 |
+
'vector_score': vector_score
|
| 243 |
})
|
| 244 |
|
| 245 |
+
# 排序並取 Top-K
|
| 246 |
+
initial_results.sort(key=lambda x: x['vector_score'], reverse=True)
|
| 247 |
+
candidates = initial_results[:top_k]
|
| 248 |
+
|
| 249 |
+
if not candidates:
|
| 250 |
+
return []
|
| 251 |
+
|
| 252 |
+
# Step 3: LLM 重排序
|
| 253 |
+
rerank_prompt = build_reranking_prompt(query, candidates[:10]) # 只重排序前10個
|
| 254 |
+
|
| 255 |
+
try:
|
| 256 |
+
response = openai_client.chat.completions.create(
|
| 257 |
+
model="gpt-4o-mini",
|
| 258 |
+
messages=[
|
| 259 |
+
{"role": "system", "content": "你是一個精準的訪談內容排序系統。"},
|
| 260 |
+
{"role": "user", "content": rerank_prompt}
|
| 261 |
+
],
|
| 262 |
+
temperature=0.1,
|
| 263 |
+
response_format={"type": "json_object"}
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
rerank_results = json.loads(response.choices[0].message.content)
|
| 267 |
+
|
| 268 |
+
# Step 4: 加權計分 (0.3 * vector + 0.7 * llm)
|
| 269 |
+
final_results = []
|
| 270 |
+
for i, candidate in enumerate(candidates[:10]):
|
| 271 |
+
llm_score = 0.5 # 預設分數
|
| 272 |
+
|
| 273 |
+
# 從 LLM 結果中找到對應的分數
|
| 274 |
+
if 'results' in rerank_results:
|
| 275 |
+
for r in rerank_results['results']:
|
| 276 |
+
if r.get('index') == i:
|
| 277 |
+
llm_score = r.get('relevance_score', 0.5)
|
| 278 |
+
break
|
| 279 |
+
|
| 280 |
+
# 計算加權分數
|
| 281 |
+
weighted_score = 0.3 * candidate['vector_score'] + 0.7 * llm_score
|
| 282 |
+
|
| 283 |
+
final_results.append(SearchResult(
|
| 284 |
+
text=candidate['text'],
|
| 285 |
+
speaker=candidate['speaker'],
|
| 286 |
+
turn_index=candidate['turn_index'],
|
| 287 |
+
file_id=candidate['file_id'],
|
| 288 |
+
vector_score=candidate['vector_score'],
|
| 289 |
+
llm_score=llm_score,
|
| 290 |
+
weighted_score=weighted_score
|
| 291 |
+
))
|
| 292 |
+
|
| 293 |
+
# 加入剩餘的候選(未經 LLM 重排序的)
|
| 294 |
+
for candidate in candidates[10:]:
|
| 295 |
+
final_results.append(SearchResult(
|
| 296 |
+
text=candidate['text'],
|
| 297 |
+
speaker=candidate['speaker'],
|
| 298 |
+
turn_index=candidate['turn_index'],
|
| 299 |
+
file_id=candidate['file_id'],
|
| 300 |
+
vector_score=candidate['vector_score'],
|
| 301 |
+
llm_score=0.0,
|
| 302 |
+
weighted_score=candidate['vector_score'] * 0.3
|
| 303 |
+
))
|
| 304 |
+
|
| 305 |
+
# 按加權分數排序
|
| 306 |
+
final_results.sort(key=lambda x: x.weighted_score, reverse=True)
|
| 307 |
+
|
| 308 |
+
# Step 5: 上下文擴展(turn_index ±10)
|
| 309 |
+
expanded_results = expand_context_by_turn_index(final_results[:5])
|
| 310 |
+
|
| 311 |
+
return expanded_results
|
| 312 |
+
|
| 313 |
+
except Exception as e:
|
| 314 |
+
print(f"LLM 重排序失敗,使用向量分數: {str(e)}")
|
| 315 |
+
# 降級處理:只使用向量分數
|
| 316 |
+
return [SearchResult(
|
| 317 |
+
text=c['text'],
|
| 318 |
+
speaker=c['speaker'],
|
| 319 |
+
turn_index=c['turn_index'],
|
| 320 |
+
file_id=c['file_id'],
|
| 321 |
+
vector_score=c['vector_score'],
|
| 322 |
+
llm_score=0.0,
|
| 323 |
+
weighted_score=c['vector_score']
|
| 324 |
+
) for c in candidates[:top_k]]
|
| 325 |
+
|
| 326 |
except Exception as e:
|
| 327 |
+
print(f"智慧路由失敗: {str(e)}")
|
| 328 |
return []
|
| 329 |
|
| 330 |
+
def expand_context_by_turn_index(search_results: List[SearchResult], context_window: int = 10) -> List[SearchResult]:
|
| 331 |
+
"""根據 turn_index 擴展上下文"""
|
| 332 |
+
expanded_results = []
|
| 333 |
+
added_indexes = set()
|
|
|
|
|
|
|
|
|
|
| 334 |
|
| 335 |
+
for result in search_results:
|
| 336 |
+
# 添加原始結果
|
| 337 |
+
if result.turn_index not in added_indexes:
|
| 338 |
+
expanded_results.append(result)
|
| 339 |
+
added_indexes.add(result.turn_index)
|
| 340 |
+
|
| 341 |
+
# 查找前後文
|
| 342 |
+
target_turn = result.turn_index
|
| 343 |
+
for item in dataset:
|
| 344 |
+
item_turn = item.get('turn_index', 0)
|
| 345 |
+
|
| 346 |
+
# 檢查是否在範圍內
|
| 347 |
+
if abs(item_turn - target_turn) <= context_window and item_turn not in added_indexes:
|
| 348 |
+
# 檢查是否為同一發言人或相關發言人
|
| 349 |
+
if item['speaker'] not in INTERVIEWERS:
|
| 350 |
+
context_result = SearchResult(
|
| 351 |
+
text=item.get('text', ''),
|
| 352 |
+
speaker=item.get('speaker', ''),
|
| 353 |
+
turn_index=item_turn,
|
| 354 |
+
file_id=item.get('file_id', ''),
|
| 355 |
+
vector_score=0.0,
|
| 356 |
+
llm_score=0.0,
|
| 357 |
+
weighted_score=result.weighted_score * 0.5 # 上下文權重降低
|
| 358 |
+
)
|
| 359 |
+
expanded_results.append(context_result)
|
| 360 |
+
added_indexes.add(item_turn)
|
| 361 |
+
|
| 362 |
+
return expanded_results
|
| 363 |
|
| 364 |
# ==========================================
|
| 365 |
+
# RAG 對話函數(每次獨立調用 API)
|
| 366 |
# ==========================================
|
| 367 |
def rag_chat(question, selected_speakers, history):
|
| 368 |
+
"""RAG 對話處理 - 每次獨立調用避免幻覺"""
|
| 369 |
if not init_success:
|
| 370 |
return history + [[question, "系統尚未初始化,請稍後再試。"]]
|
| 371 |
|
| 372 |
try:
|
| 373 |
+
# 執行智慧路由與重排序
|
| 374 |
+
search_results = intelligent_routing_and_reranking(question, selected_speakers, top_k=20)
|
| 375 |
|
| 376 |
if not search_results:
|
| 377 |
return history + [[question, "未找到相關內容,請嘗試其他問題。"]]
|
| 378 |
|
| 379 |
+
# 構建上下文(包含原始 RAG 內容)
|
| 380 |
context = "相關訪談內容:\n\n"
|
| 381 |
+
raw_contexts = []
|
| 382 |
+
|
| 383 |
+
for i, result in enumerate(search_results[:5], 1):
|
| 384 |
context += f"[片段 {i}]\n"
|
| 385 |
+
context += f"發言人:{result.speaker}\n"
|
| 386 |
+
context += f"內容:{result.text}\n"
|
| 387 |
+
context += f"相關性分數:向量={result.vector_score:.3f}, LLM={result.llm_score:.3f}, 加權={result.weighted_score:.3f}\n\n"
|
| 388 |
+
|
| 389 |
+
# 保存原始內容
|
| 390 |
+
raw_contexts.append(f"[{result.speaker} - Turn {result.turn_index}]: {result.text}")
|
| 391 |
|
| 392 |
+
# 構建 GPT prompt(每次獨立,不包含歷史)
|
| 393 |
+
prompt = f"""基於以下訪談內容回答問題。請提供準確、完整的回答。
|
| 394 |
|
| 395 |
{context}
|
| 396 |
|
| 397 |
問題:{question}
|
| 398 |
|
| 399 |
+
要求:
|
| 400 |
+
1. 基於提供的訪談內容回答
|
| 401 |
+
2. 引用具體的發言人和內容
|
| 402 |
+
3. 如果內容不足以回答,請明確說明"""
|
| 403 |
+
|
| 404 |
+
# 調用 GPT(每次獨立調用)
|
| 405 |
+
response = openai_client.chat.completions.create(
|
| 406 |
+
model="gpt-4o-mini",
|
| 407 |
+
messages=[
|
| 408 |
+
{"role": "system", "content": "你是一個專業的訪談分析助手。只基於提供的內容回答,不要添加額外信息。"},
|
| 409 |
+
{"role": "user", "content": prompt}
|
| 410 |
+
],
|
| 411 |
+
temperature=0.1
|
| 412 |
+
)
|
| 413 |
+
|
| 414 |
+
answer = response.choices[0].message.content
|
| 415 |
|
| 416 |
+
# 添加原始 RAG 內容
|
| 417 |
+
answer_with_sources = f"{answer}\n\n---\n📚 **原始 RAG 來源:**\n"
|
| 418 |
+
for i, raw_context in enumerate(raw_contexts[:3], 1):
|
| 419 |
+
answer_with_sources += f"\n{i}. {raw_context[:200]}...\n"
|
| 420 |
|
| 421 |
+
return history + [[question, answer_with_sources]]
|
| 422 |
|
| 423 |
except Exception as e:
|
| 424 |
return history + [[question, f"處理過程中發生錯誤:{str(e)}"]]
|
| 425 |
|
| 426 |
# ==========================================
|
| 427 |
+
# 訪綱填答函數(包含原始 RAG 內容)
|
| 428 |
# ==========================================
|
| 429 |
def parse_word_document(file_path):
|
| 430 |
"""解析 Word 文檔中的問題"""
|
|
|
|
| 434 |
|
| 435 |
for para in doc.paragraphs:
|
| 436 |
text = para.text.strip()
|
|
|
|
| 437 |
if text and (
|
| 438 |
any(char in text for char in ['?', '?']) or
|
| 439 |
+
(text[0].isdigit() if text else False) or
|
| 440 |
text.startswith(('Q', '問'))
|
| 441 |
):
|
| 442 |
questions.append(text)
|
|
|
|
| 446 |
print(f"解析文檔失敗: {str(e)}")
|
| 447 |
return []
|
| 448 |
|
| 449 |
+
def single_interviewee_guide_filling(file_path, selected_speakers):
|
| 450 |
+
"""單一受訪者訪綱填答 - 整合冠軍策略"""
|
| 451 |
if not init_success:
|
| 452 |
return None, "系統尚未初始化"
|
| 453 |
|
| 454 |
try:
|
| 455 |
+
# 解析 Word 訪綱
|
| 456 |
questions = parse_word_document(file_path)
|
| 457 |
|
| 458 |
if not questions:
|
| 459 |
+
return None, "未能從文檔中提取問題"
|
| 460 |
|
| 461 |
# 創建新的 Word 文檔
|
| 462 |
output_doc = Document()
|
| 463 |
+
output_doc.add_heading('訪談訪綱 - AI 智慧填答', 0)
|
| 464 |
output_doc.add_paragraph(f'處理時間:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
|
| 465 |
output_doc.add_paragraph(f'選擇的受訪者:{", ".join(selected_speakers) if selected_speakers else "全部"}')
|
| 466 |
+
output_doc.add_paragraph(f'使用技術:Multilingual-E5-Large + GPT-4o-mini + 冠軍級 RAG')
|
| 467 |
output_doc.add_paragraph('')
|
| 468 |
|
| 469 |
+
# 處理每個問題(每個問題獨立調用 API)
|
| 470 |
+
for i, question in enumerate(questions[:10], 1):
|
| 471 |
+
output_doc.add_heading(f'問題 {i}', level=1)
|
|
|
|
| 472 |
output_doc.add_paragraph(question)
|
| 473 |
|
| 474 |
+
# 使用智慧路由與重排序檢索
|
| 475 |
+
search_results = intelligent_routing_and_reranking(question, selected_speakers, top_k=15)
|
| 476 |
|
| 477 |
if search_results:
|
| 478 |
# 構建上下文
|
| 479 |
context = ""
|
| 480 |
+
raw_contexts = []
|
|
|
|
|
|
|
| 481 |
|
| 482 |
+
for j, result in enumerate(search_results[:5]):
|
| 483 |
+
context += f"[片段 {j+1}]\n"
|
| 484 |
+
context += f"發言人:{result.speaker}\n"
|
| 485 |
+
context += f"內容:{result.text}\n"
|
| 486 |
+
context += f"相關性:向量={result.vector_score:.3f}, LLM={result.llm_score:.3f}\n\n"
|
| 487 |
+
|
| 488 |
+
raw_contexts.append({
|
| 489 |
+
'speaker': result.speaker,
|
| 490 |
+
'text': result.text,
|
| 491 |
+
'turn_index': result.turn_index,
|
| 492 |
+
'score': result.weighted_score
|
| 493 |
+
})
|
| 494 |
+
|
| 495 |
+
# 獨立調用 GPT 生成回答
|
| 496 |
+
prompt = f"""基於以下訪談內容回答訪綱問題:
|
| 497 |
|
| 498 |
{context}
|
| 499 |
|
| 500 |
問題:{question}
|
| 501 |
|
| 502 |
+
請提供:
|
| 503 |
+
1. 主要回答
|
| 504 |
+
2. 不同受訪者的觀點(如果有)
|
| 505 |
+
3. 具體引述"""
|
| 506 |
+
|
| 507 |
+
response = openai_client.chat.completions.create(
|
| 508 |
+
model="gpt-4o-mini",
|
| 509 |
+
messages=[
|
| 510 |
+
{"role": "system", "content": "你是訪談分析專家。基於提供的內容準確回答。"},
|
| 511 |
+
{"role": "user", "content": prompt}
|
| 512 |
+
],
|
| 513 |
+
temperature=0.1
|
| 514 |
+
)
|
| 515 |
|
| 516 |
+
answer = response.choices[0].message.content
|
| 517 |
|
| 518 |
+
# 添加 AI 回答
|
| 519 |
+
output_doc.add_heading('AI 分析回答:', level=2)
|
| 520 |
+
for line in answer.split('\n'):
|
| 521 |
+
if line.strip():
|
| 522 |
+
output_doc.add_paragraph(line)
|
| 523 |
|
| 524 |
+
# 添加原始 RAG 內容
|
| 525 |
+
output_doc.add_heading('原始 RAG 向量檢索內容:', level=2)
|
| 526 |
+
for j, raw in enumerate(raw_contexts[:3], 1):
|
| 527 |
+
p = output_doc.add_paragraph()
|
| 528 |
+
p.add_run(f"{j}. [{raw['speaker']} - Turn {raw['turn_index']}] ").bold = True
|
| 529 |
+
p.add_run(f"(相關性: {raw['score']:.3f})\n")
|
| 530 |
+
p.add_run(f"{raw['text'][:300]}...")
|
| 531 |
else:
|
| 532 |
output_doc.add_paragraph("未找到相關內容")
|
| 533 |
|
| 534 |
+
output_doc.add_page_break() # 分頁
|
| 535 |
+
|
| 536 |
+
# 添加未使用內容分析(如果是單一受訪者)
|
| 537 |
+
if len(selected_speakers) == 1:
|
| 538 |
+
output_doc.add_heading('補充:可能相關但未被問及的內容', level=1)
|
| 539 |
+
# 這裡可以加入額外的分析邏輯
|
| 540 |
|
| 541 |
# 保存文檔
|
| 542 |
output_buffer = io.BytesIO()
|
| 543 |
output_doc.save(output_buffer)
|
| 544 |
output_buffer.seek(0)
|
| 545 |
|
|
|
|
| 546 |
output_filename = f"filled_guide_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
|
| 547 |
with open(output_filename, 'wb') as f:
|
| 548 |
f.write(output_buffer.getvalue())
|
| 549 |
|
| 550 |
+
return output_filename, "訪綱填答完成!使用冠軍級 RAG 策略"
|
| 551 |
|
| 552 |
except Exception as e:
|
| 553 |
return None, f"處理失敗:{str(e)}"
|
|
|
|
| 558 |
def create_interface():
|
| 559 |
"""創建 Gradio 介面"""
|
| 560 |
|
| 561 |
+
with gr.Blocks(
|
| 562 |
+
title="訪談轉錄稿 RAG 系統",
|
| 563 |
+
theme=gr.themes.Soft(),
|
| 564 |
+
css="""
|
| 565 |
+
.gradio-container {
|
| 566 |
+
font-family: 'Microsoft JhengHei', sans-serif;
|
| 567 |
+
}
|
| 568 |
+
.markdown-text {
|
| 569 |
+
font-size: 16px;
|
| 570 |
+
}
|
| 571 |
+
"""
|
| 572 |
+
) as app:
|
| 573 |
# 標題
|
| 574 |
gr.Markdown("""
|
| 575 |
# 🎙️ 訪談轉錄稿智慧分析系統
|
| 576 |
|
| 577 |
+
**技術架構:** Multilingual-E5-Large + GPT-4o-mini + 冠軍級 RAG 策略
|
| 578 |
+
|
| 579 |
+
**核心功能:**
|
| 580 |
+
- 🔍 智慧語義搜尋與重排序
|
| 581 |
+
- 💬 AI 對話(每次獨立調用避免幻覺)
|
| 582 |
+
- 📝 訪綱自動填答(含原始 RAG 內容)
|
| 583 |
+
- 📊 加權評分機制(0.3×向量 + 0.7×LLM)
|
| 584 |
""")
|
| 585 |
|
| 586 |
# 系統狀態
|
|
|
|
| 596 |
with gr.Tabs():
|
| 597 |
# Tab 1: AI 對話
|
| 598 |
with gr.Tab("💬 AI 對話"):
|
| 599 |
+
gr.Markdown("### 智慧問答系統(每次獨立調用 API)")
|
| 600 |
+
|
| 601 |
with gr.Row():
|
| 602 |
with gr.Column(scale=1):
|
| 603 |
gr.Markdown("### 選擇受訪者")
|
|
|
|
| 610 |
with gr.Column(scale=3):
|
| 611 |
chatbot = gr.Chatbot(
|
| 612 |
height=500,
|
| 613 |
+
label="對話記錄",
|
| 614 |
+
show_label=True
|
| 615 |
)
|
| 616 |
|
| 617 |
with gr.Row():
|
|
|
|
| 622 |
)
|
| 623 |
send_btn = gr.Button("發送", variant="primary", scale=1)
|
| 624 |
|
| 625 |
+
with gr.Row():
|
| 626 |
+
clear_btn = gr.Button("清除對話")
|
| 627 |
+
gr.Markdown("*每個問題都會獨立調用 API,避免產生幻覺*")
|
| 628 |
|
| 629 |
# Tab 2: 訪綱填答
|
| 630 |
with gr.Tab("📝 訪綱填答"):
|
| 631 |
gr.Markdown("""
|
| 632 |
+
### 智慧訪綱填答系統
|
| 633 |
+
|
| 634 |
+
**特色功能:**
|
| 635 |
+
- 使用冠軍級 RAG 策略
|
| 636 |
+
- 每個問題獨立處理
|
| 637 |
+
- 顯示原始 RAG 檢索內容
|
| 638 |
+
- 加權評分機制
|
| 639 |
""")
|
| 640 |
|
| 641 |
with gr.Row():
|
|
|
|
| 643 |
guide_speakers = gr.CheckboxGroup(
|
| 644 |
choices=[],
|
| 645 |
label="選擇受訪者",
|
| 646 |
+
info="建議選擇單一受訪者以獲得最佳效果"
|
| 647 |
)
|
| 648 |
|
| 649 |
file_input = gr.File(
|
|
|
|
| 664 |
visible=False
|
| 665 |
)
|
| 666 |
|
| 667 |
+
# 技術細節
|
| 668 |
+
with gr.Accordion("🔧 技術細節", open=False):
|
| 669 |
gr.Markdown("""
|
| 670 |
+
### 冠軍級 RAG 技術實現
|
| 671 |
+
|
| 672 |
+
**1. 向量化處理**
|
| 673 |
+
- 模型:Multilingual-E5-Large
|
| 674 |
+
- 格式:結合 speaker + content
|
| 675 |
+
- 前綴:query: / passage:
|
| 676 |
+
|
| 677 |
+
**2. 智慧路由與重排序**
|
| 678 |
+
- 初步檢索:Top-30 向量相似度
|
| 679 |
+
- LLM 重排序:GPT-4o-mini 評分
|
| 680 |
+
- 加權計算:0.3×向量 + 0.7×LLM
|
| 681 |
+
- 上下文擴展:±10 turn_index
|
| 682 |
+
|
| 683 |
+
**3. 防止幻覺機制**
|
| 684 |
+
- 每次問題獨立調用 API
|
| 685 |
+
- 不傳遞歷史對話上下文
|
| 686 |
+
- 顯示原始 RAG 來源
|
| 687 |
""")
|
| 688 |
|
| 689 |
# 事件處理
|
|
|
|
| 700 |
if not file:
|
| 701 |
return "請上傳文件", gr.File(visible=False)
|
| 702 |
|
| 703 |
+
result_file, status = single_interviewee_guide_filling(file.name, speakers)
|
| 704 |
|
| 705 |
if result_file:
|
| 706 |
return status, gr.File(value=result_file, visible=True)
|
|
|
|
| 710 |
def update_status():
|
| 711 |
success, message = initialize_system()
|
| 712 |
if success:
|
|
|
|
| 713 |
return (
|
| 714 |
message,
|
| 715 |
gr.CheckboxGroup(choices=all_speakers),
|