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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
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
|
| 12 |
+
from docx import Document
|
| 13 |
+
import io
|
| 14 |
+
from typing import List, Dict, Any, Optional, Tuple
|
| 15 |
+
|
| 16 |
+
# ==========================================
|
| 17 |
+
# 環境變數設定
|
| 18 |
+
# ==========================================
|
| 19 |
+
# 從 Hugging Face Secrets 讀取
|
| 20 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 21 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
|
| 22 |
+
|
| 23 |
+
# 資料集配置
|
| 24 |
+
DATASET_NAME = "s880453/interview-transcripts-vectorized"
|
| 25 |
+
EMBEDDING_MODEL = "intfloat/multilingual-e5-large"
|
| 26 |
+
|
| 27 |
+
# 採訪者名單(需要排除)
|
| 28 |
+
INTERVIEWERS = ["徐美苓", "許弘諺", "郭禹彤"]
|
| 29 |
+
|
| 30 |
+
# ==========================================
|
| 31 |
+
# 全域變數
|
| 32 |
+
# ==========================================
|
| 33 |
+
dataset = None
|
| 34 |
+
embeddings = None
|
| 35 |
+
tokenizer = None
|
| 36 |
+
model = None
|
| 37 |
+
openai_client = None
|
| 38 |
+
all_speakers = []
|
| 39 |
+
|
| 40 |
+
# ==========================================
|
| 41 |
+
# 初始化函數
|
| 42 |
+
# ==========================================
|
| 43 |
+
def initialize_system():
|
| 44 |
+
"""初始化系統"""
|
| 45 |
+
global dataset, embeddings, tokenizer, model, openai_client, all_speakers
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
print("🔄 正在初始化系統...")
|
| 49 |
+
|
| 50 |
+
# 初始化 OpenAI
|
| 51 |
+
openai_client = OpenAI(api_key=OPENAI_API_KEY)
|
| 52 |
+
print("✅ OpenAI 客戶端初始化成功")
|
| 53 |
+
|
| 54 |
+
# 載入資料集
|
| 55 |
+
print(f"📊 正在載入資料集: {DATASET_NAME}")
|
| 56 |
+
dataset = load_dataset(DATASET_NAME, split="train", token=HF_TOKEN)
|
| 57 |
+
print(f"✅ 資料集載入成功,共 {len(dataset)} 筆資料")
|
| 58 |
+
|
| 59 |
+
# 提取所有嵌入向量
|
| 60 |
+
embeddings = np.array([item['embedding'] for item in dataset])
|
| 61 |
+
print(f"✅ 嵌入向量提取成功,維度: {embeddings.shape}")
|
| 62 |
+
|
| 63 |
+
# 載入嵌入模型
|
| 64 |
+
print(f"🤖 正在載入模型: {EMBEDDING_MODEL}")
|
| 65 |
+
tokenizer = AutoTokenizer.from_pretrained(EMBEDDING_MODEL)
|
| 66 |
+
model = AutoModel.from_pretrained(EMBEDDING_MODEL)
|
| 67 |
+
print("✅ 嵌入模型載入成功")
|
| 68 |
+
|
| 69 |
+
# 提取所有發言人(排除採訪者)
|
| 70 |
+
all_speakers_set = set()
|
| 71 |
+
for item in dataset:
|
| 72 |
+
speaker = item['speaker']
|
| 73 |
+
if speaker not in INTERVIEWERS:
|
| 74 |
+
all_speakers_set.add(speaker)
|
| 75 |
+
all_speakers = sorted(list(all_speakers_set))
|
| 76 |
+
print(f"✅ 發言人列表提取成功,共 {len(all_speakers)} 位受訪者")
|
| 77 |
+
|
| 78 |
+
return True, "系統初始化成功!"
|
| 79 |
+
|
| 80 |
+
except Exception as e:
|
| 81 |
+
error_msg = f"系統初始化失敗: {str(e)}"
|
| 82 |
+
print(f"❌ {error_msg}")
|
| 83 |
+
return False, error_msg
|
| 84 |
+
|
| 85 |
+
# ==========================================
|
| 86 |
+
# 向量搜尋函數
|
| 87 |
+
# ==========================================
|
| 88 |
+
def average_pool(last_hidden_states, attention_mask):
|
| 89 |
+
"""Average pooling for embeddings"""
|
| 90 |
+
last_hidden = last_hidden_states.masked_fill(~attention_mask[..., None].bool(), 0.0)
|
| 91 |
+
return last_hidden.sum(dim=1) / attention_mask.sum(dim=1)[..., None]
|
| 92 |
+
|
| 93 |
+
def generate_query_embedding(query_text):
|
| 94 |
+
"""生成查詢向量"""
|
| 95 |
+
# 添加查詢前綴
|
| 96 |
+
query_with_prefix = f"query: {query_text}"
|
| 97 |
+
|
| 98 |
+
# Tokenize
|
| 99 |
+
inputs = tokenizer(
|
| 100 |
+
[query_with_prefix],
|
| 101 |
+
max_length=512,
|
| 102 |
+
padding=True,
|
| 103 |
+
truncation=True,
|
| 104 |
+
return_tensors='pt'
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# 生成嵌入
|
| 108 |
+
with torch.no_grad():
|
| 109 |
+
outputs = model(**inputs)
|
| 110 |
+
query_embedding = average_pool(outputs.last_hidden_state, inputs['attention_mask'])
|
| 111 |
+
query_embedding = torch.nn.functional.normalize(query_embedding, p=2, dim=1)
|
| 112 |
+
|
| 113 |
+
return query_embedding.cpu().numpy()[0]
|
| 114 |
+
|
| 115 |
+
def semantic_search(query, selected_speakers, top_k=20):
|
| 116 |
+
"""語義搜尋"""
|
| 117 |
+
if not dataset:
|
| 118 |
+
return []
|
| 119 |
+
|
| 120 |
+
# 生成查詢向量
|
| 121 |
+
query_vector = generate_query_embedding(query)
|
| 122 |
+
|
| 123 |
+
# 計算相似度
|
| 124 |
+
similarities = []
|
| 125 |
+
for i, item in enumerate(dataset):
|
| 126 |
+
# 檢查發言人過濾
|
| 127 |
+
if selected_speakers and item['speaker'] not in selected_speakers:
|
| 128 |
+
continue
|
| 129 |
+
|
| 130 |
+
# 計算餘弦相似度
|
| 131 |
+
item_vector = np.array(item['embedding'])
|
| 132 |
+
similarity = np.dot(query_vector, item_vector)
|
| 133 |
+
|
| 134 |
+
similarities.append({
|
| 135 |
+
'score': float(similarity),
|
| 136 |
+
'text': item['text'],
|
| 137 |
+
'speaker': item['speaker'],
|
| 138 |
+
'turn_index': item['turn_index'],
|
| 139 |
+
'file_id': item['file_id']
|
| 140 |
+
})
|
| 141 |
+
|
| 142 |
+
# 排序並返回前 k 個結果
|
| 143 |
+
similarities.sort(key=lambda x: x['score'], reverse=True)
|
| 144 |
+
return similarities[:top_k]
|
| 145 |
+
|
| 146 |
+
# ==========================================
|
| 147 |
+
# GPT-4o-mini 處理函數
|
| 148 |
+
# ==========================================
|
| 149 |
+
def call_gpt4o_mini(prompt, temperature=0.1):
|
| 150 |
+
"""調用 GPT-4o-mini"""
|
| 151 |
+
try:
|
| 152 |
+
response = openai_client.chat.completions.create(
|
| 153 |
+
model="gpt-4o-mini",
|
| 154 |
+
messages=[
|
| 155 |
+
{"role": "system", "content": "你是一個專業的訪談分析助手,擅長從訪談內容中提取關鍵信息並回答問題。"},
|
| 156 |
+
{"role": "user", "content": prompt}
|
| 157 |
+
],
|
| 158 |
+
temperature=temperature
|
| 159 |
+
)
|
| 160 |
+
return response.choices[0].message.content
|
| 161 |
+
except Exception as e:
|
| 162 |
+
return f"GPT 調用失敗: {str(e)}"
|
| 163 |
+
|
| 164 |
+
# ==========================================
|
| 165 |
+
# RAG 對話函數
|
| 166 |
+
# ==========================================
|
| 167 |
+
def rag_chat(question, selected_speakers, history):
|
| 168 |
+
"""RAG 對話處理"""
|
| 169 |
+
if not dataset:
|
| 170 |
+
return history + [[question, "系統尚未初始化,請稍後再試。"]]
|
| 171 |
+
|
| 172 |
+
try:
|
| 173 |
+
# 執行語義搜尋
|
| 174 |
+
search_results = semantic_search(question, selected_speakers, top_k=10)
|
| 175 |
+
|
| 176 |
+
if not search_results:
|
| 177 |
+
return history + [[question, "未找到相關內容,請嘗試其他問題。"]]
|
| 178 |
+
|
| 179 |
+
# 構建上下文
|
| 180 |
+
context = "相關訪談內容:\n\n"
|
| 181 |
+
for i, result in enumerate(search_results, 1):
|
| 182 |
+
context += f"[片段 {i}]\n"
|
| 183 |
+
context += f"發言人:{result['speaker']}\n"
|
| 184 |
+
context += f"內容:{result['text']}\n"
|
| 185 |
+
context += f"相似度:{result['score']:.3f}\n\n"
|
| 186 |
+
|
| 187 |
+
# 構建 GPT prompt
|
| 188 |
+
prompt = f"""基於以下訪談內容回答問題。
|
| 189 |
+
|
| 190 |
+
{context}
|
| 191 |
+
|
| 192 |
+
問題:{question}
|
| 193 |
+
|
| 194 |
+
請提供準確、完整的回答,並在適當時引用具體的發言人和內容。"""
|
| 195 |
+
|
| 196 |
+
# 調用 GPT
|
| 197 |
+
answer = call_gpt4o_mini(prompt)
|
| 198 |
+
|
| 199 |
+
return history + [[question, answer]]
|
| 200 |
+
|
| 201 |
+
except Exception as e:
|
| 202 |
+
return history + [[question, f"處理過程中發生錯誤:{str(e)}"]]
|
| 203 |
+
|
| 204 |
+
# ==========================================
|
| 205 |
+
# 訪綱填答函數
|
| 206 |
+
# ==========================================
|
| 207 |
+
def parse_word_document(file):
|
| 208 |
+
"""解析 Word 文檔中的問題"""
|
| 209 |
+
try:
|
| 210 |
+
doc = Document(file)
|
| 211 |
+
questions = []
|
| 212 |
+
|
| 213 |
+
for para in doc.paragraphs:
|
| 214 |
+
text = para.text.strip()
|
| 215 |
+
# 識別問題(以數字、問號或特定格式開頭)
|
| 216 |
+
if text and (
|
| 217 |
+
text[0].isdigit() or
|
| 218 |
+
'?' in text or
|
| 219 |
+
'?' in text or
|
| 220 |
+
text.startswith('Q') or
|
| 221 |
+
text.startswith('問')
|
| 222 |
+
):
|
| 223 |
+
questions.append(text)
|
| 224 |
+
|
| 225 |
+
return questions
|
| 226 |
+
except Exception as e:
|
| 227 |
+
return []
|
| 228 |
+
|
| 229 |
+
def fill_interview_guide(file, selected_speakers):
|
| 230 |
+
"""填答訪綱"""
|
| 231 |
+
if not dataset:
|
| 232 |
+
return None, "系統尚未初始化"
|
| 233 |
+
|
| 234 |
+
try:
|
| 235 |
+
# 解析 Word 文檔
|
| 236 |
+
questions = parse_word_document(file)
|
| 237 |
+
|
| 238 |
+
if not questions:
|
| 239 |
+
return None, "未能從文檔中提取問題,請確認格式"
|
| 240 |
+
|
| 241 |
+
# 創建新的 Word 文檔
|
| 242 |
+
output_doc = Document()
|
| 243 |
+
output_doc.add_heading('訪談訪綱 - AI 自動填答', 0)
|
| 244 |
+
output_doc.add_paragraph(f'處理時間:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
|
| 245 |
+
output_doc.add_paragraph(f'選擇的受訪者:{", ".join(selected_speakers) if selected_speakers else "全部"}')
|
| 246 |
+
output_doc.add_paragraph('')
|
| 247 |
+
|
| 248 |
+
# 處理每個問題
|
| 249 |
+
for i, question in enumerate(questions, 1):
|
| 250 |
+
# 添加問題
|
| 251 |
+
output_doc.add_heading(f'問題 {i}', level=2)
|
| 252 |
+
output_doc.add_paragraph(question)
|
| 253 |
+
|
| 254 |
+
# 搜尋相關內容
|
| 255 |
+
search_results = semantic_search(question, selected_speakers, top_k=5)
|
| 256 |
+
|
| 257 |
+
if search_results:
|
| 258 |
+
# 構建上下文
|
| 259 |
+
context = ""
|
| 260 |
+
for result in search_results:
|
| 261 |
+
context += f"發言人:{result['speaker']}\n"
|
| 262 |
+
context += f"內容:{result['text']}\n\n"
|
| 263 |
+
|
| 264 |
+
# 使用 GPT 生成回答
|
| 265 |
+
prompt = f"""基於以下訪談內容回答問題:
|
| 266 |
+
|
| 267 |
+
{context}
|
| 268 |
+
|
| 269 |
+
問題:{question}
|
| 270 |
+
|
| 271 |
+
請提供結構化的回答,包含:
|
| 272 |
+
1. 主要觀點
|
| 273 |
+
2. 不同受訪者的觀點(如果有多位)
|
| 274 |
+
3. 具體引述"""
|
| 275 |
+
|
| 276 |
+
answer = call_gpt4o_mini(prompt)
|
| 277 |
+
|
| 278 |
+
# 添加回答
|
| 279 |
+
output_doc.add_heading('回答:', level=3)
|
| 280 |
+
for line in answer.split('\n'):
|
| 281 |
+
if line.strip():
|
| 282 |
+
output_doc.add_paragraph(line)
|
| 283 |
+
|
| 284 |
+
# 添加相關引述
|
| 285 |
+
output_doc.add_heading('相關引述:', level=3)
|
| 286 |
+
for j, result in enumerate(search_results[:3], 1):
|
| 287 |
+
p = output_doc.add_paragraph()
|
| 288 |
+
p.add_run(f"{j}. {result['speaker']}:").bold = True
|
| 289 |
+
p.add_run(f" {result['text'][:200]}...")
|
| 290 |
+
else:
|
| 291 |
+
output_doc.add_paragraph("未找到相關內容")
|
| 292 |
+
|
| 293 |
+
output_doc.add_paragraph('') # 空行分隔
|
| 294 |
+
|
| 295 |
+
# 保存文檔
|
| 296 |
+
output_buffer = io.BytesIO()
|
| 297 |
+
output_doc.save(output_buffer)
|
| 298 |
+
output_buffer.seek(0)
|
| 299 |
+
|
| 300 |
+
return output_buffer, "訪綱填答完成!"
|
| 301 |
+
|
| 302 |
+
except Exception as e:
|
| 303 |
+
return None, f"處理失敗:{str(e)}"
|
| 304 |
+
|
| 305 |
+
# ==========================================
|
| 306 |
+
# Gradio 介面
|
| 307 |
+
# ==========================================
|
| 308 |
+
def create_interface():
|
| 309 |
+
"""創建 Gradio 介面"""
|
| 310 |
+
|
| 311 |
+
with gr.Blocks(title="訪談轉錄稿 RAG 系統", theme=gr.themes.Soft()) as app:
|
| 312 |
+
# 標題
|
| 313 |
+
gr.Markdown("""
|
| 314 |
+
# 🎙️ 訪談轉錄稿智慧分析系統
|
| 315 |
+
|
| 316 |
+
基於 RAG 技術的訪談內容分析與問答系統
|
| 317 |
+
""")
|
| 318 |
+
|
| 319 |
+
# 系統狀態
|
| 320 |
+
with gr.Row():
|
| 321 |
+
status_text = gr.Textbox(
|
| 322 |
+
label="系統狀態",
|
| 323 |
+
value="初始化中...",
|
| 324 |
+
interactive=False
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# 主要功能區
|
| 328 |
+
with gr.Tabs():
|
| 329 |
+
# Tab 1: AI 對話
|
| 330 |
+
with gr.Tab("💬 AI 對話"):
|
| 331 |
+
with gr.Row():
|
| 332 |
+
with gr.Column(scale=1):
|
| 333 |
+
gr.Markdown("### 選擇受訪者")
|
| 334 |
+
speaker_selector = gr.CheckboxGroup(
|
| 335 |
+
choices=all_speakers,
|
| 336 |
+
label="受訪者列表",
|
| 337 |
+
info="不選擇則搜尋全部內容"
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
with gr.Column(scale=3):
|
| 341 |
+
chatbot = gr.Chatbot(
|
| 342 |
+
height=500,
|
| 343 |
+
label="對話記錄"
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
with gr.Row():
|
| 347 |
+
msg = gr.Textbox(
|
| 348 |
+
label="輸入問題",
|
| 349 |
+
placeholder="請輸入您想詢問的問題...",
|
| 350 |
+
scale=4
|
| 351 |
+
)
|
| 352 |
+
send_btn = gr.Button("發送", variant="primary", scale=1)
|
| 353 |
+
|
| 354 |
+
clear_btn = gr.Button("清除對話")
|
| 355 |
+
|
| 356 |
+
# Tab 2: 訪綱填答
|
| 357 |
+
with gr.Tab("📝 訪綱填答"):
|
| 358 |
+
gr.Markdown("""
|
| 359 |
+
### 使用說明
|
| 360 |
+
1. 選擇要分析的受訪者
|
| 361 |
+
2. 上傳 Word 格式的訪綱文件
|
| 362 |
+
3. 系統將自動識別問題並填答
|
| 363 |
+
4. 下載完成的文檔
|
| 364 |
+
""")
|
| 365 |
+
|
| 366 |
+
with gr.Row():
|
| 367 |
+
with gr.Column():
|
| 368 |
+
guide_speakers = gr.CheckboxGroup(
|
| 369 |
+
choices=all_speakers,
|
| 370 |
+
label="選擇受訪者",
|
| 371 |
+
info="不選擇則分析全部受訪者"
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
file_input = gr.File(
|
| 375 |
+
label="上傳訪綱 (Word 格式)",
|
| 376 |
+
file_types=[".docx", ".doc"]
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
process_btn = gr.Button("開始處理", variant="primary")
|
| 380 |
+
|
| 381 |
+
with gr.Column():
|
| 382 |
+
process_status = gr.Textbox(
|
| 383 |
+
label="處理狀態",
|
| 384 |
+
interactive=False
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
download_file = gr.File(
|
| 388 |
+
label="下載結果",
|
| 389 |
+
visible=False
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
# 關於
|
| 393 |
+
with gr.Accordion("ℹ️ 關於系統", open=False):
|
| 394 |
+
gr.Markdown("""
|
| 395 |
+
### 系統資訊
|
| 396 |
+
- **向量模型**: multilingual-e5-large
|
| 397 |
+
- **語言模型**: GPT-4o-mini
|
| 398 |
+
- **資料來源**: Hugging Face Dataset
|
| 399 |
+
- **版本**: 1.0.0
|
| 400 |
+
|
| 401 |
+
### 功能特色
|
| 402 |
+
- 🔍 智慧語義搜尋
|
| 403 |
+
- 💬 自然語言問答
|
| 404 |
+
- 📝 自動訪綱填答
|
| 405 |
+
- 👥 多受訪者分析
|
| 406 |
+
""")
|
| 407 |
+
|
| 408 |
+
# 事件處理
|
| 409 |
+
def send_message(message, speakers, history):
|
| 410 |
+
if not message:
|
| 411 |
+
return "", history
|
| 412 |
+
new_history = rag_chat(message, speakers, history)
|
| 413 |
+
return "", new_history
|
| 414 |
+
|
| 415 |
+
def clear_chat():
|
| 416 |
+
return []
|
| 417 |
+
|
| 418 |
+
def process_guide(file, speakers):
|
| 419 |
+
if not file:
|
| 420 |
+
return "請上傳文件", None
|
| 421 |
+
|
| 422 |
+
result_file, status = fill_interview_guide(file.name, speakers)
|
| 423 |
+
|
| 424 |
+
if result_file:
|
| 425 |
+
# 保存到臨時文件
|
| 426 |
+
temp_path = f"filled_guide_{datetime.now().strftime('%Y%m%d_%H%M%S')}.docx"
|
| 427 |
+
with open(temp_path, 'wb') as f:
|
| 428 |
+
f.write(result_file.getvalue())
|
| 429 |
+
return status, gr.File(value=temp_path, visible=True)
|
| 430 |
+
else:
|
| 431 |
+
return status, None
|
| 432 |
+
|
| 433 |
+
# 綁定事件
|
| 434 |
+
send_btn.click(
|
| 435 |
+
send_message,
|
| 436 |
+
inputs=[msg, speaker_selector, chatbot],
|
| 437 |
+
outputs=[msg, chatbot]
|
| 438 |
+
)
|
| 439 |
+
|
| 440 |
+
msg.submit(
|
| 441 |
+
send_message,
|
| 442 |
+
inputs=[msg, speaker_selector, chatbot],
|
| 443 |
+
outputs=[msg, chatbot]
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
clear_btn.click(clear_chat, outputs=[chatbot])
|
| 447 |
+
|
| 448 |
+
process_btn.click(
|
| 449 |
+
process_guide,
|
| 450 |
+
inputs=[file_input, guide_speakers],
|
| 451 |
+
outputs=[process_status, download_file]
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
# 初始化系統
|
| 455 |
+
def update_status():
|
| 456 |
+
success, message = initialize_system()
|
| 457 |
+
if success:
|
| 458 |
+
# 更新發言人列表
|
| 459 |
+
speaker_selector.choices = all_speakers
|
| 460 |
+
guide_speakers.choices = all_speakers
|
| 461 |
+
return message
|
| 462 |
+
|
| 463 |
+
app.load(update_status, outputs=[status_text])
|
| 464 |
+
|
| 465 |
+
return app
|
| 466 |
+
|
| 467 |
+
# ==========================================
|
| 468 |
+
# 主程式入口
|
| 469 |
+
# ==========================================
|
| 470 |
+
if __name__ == "__main__":
|
| 471 |
+
# 創建並啟動應用
|
| 472 |
+
app = create_interface()
|
| 473 |
+
app.launch(
|
| 474 |
+
share=False,
|
| 475 |
+
server_name="0.0.0.0",
|
| 476 |
+
server_port=7860
|
| 477 |
+
)
|