Spaces:
Sleeping
Sleeping
File size: 20,419 Bytes
1687ca3 b11b466 1687ca3 b11b466 1687ca3 b11b466 1687ca3 b11b466 40774bb 1687ca3 b11b466 40774bb b11b466 1687ca3 b11b466 1687ca3 b11b466 1687ca3 2bf436a b11b466 1687ca3 b11b466 1687ca3 b11b466 1687ca3 b11b466 2bf436a b11b466 1687ca3 b11b466 1687ca3 b11b466 89f9915 c67d332 89f9915 c67d332 2fafc2b c67d332 89f9915 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 a119ef4 2fafc2b c67d332 a119ef4 c67d332 a119ef4 2fafc2b a119ef4 c67d332 2fafc2b a119ef4 2fafc2b a119ef4 c67d332 a119ef4 c67d332 a119ef4 2fafc2b a119ef4 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 89f9915 b11b466 c67d332 2fafc2b c67d332 2fafc2b 89f9915 c67d332 2fafc2b 89f9915 a119ef4 c67d332 2fafc2b 89f9915 a119ef4 2fafc2b c67d332 2fafc2b c67d332 2fafc2b c67d332 2fafc2b b11b466 2fafc2b a119ef4 b11b466 2fafc2b b11b466 2fafc2b b11b466 1687ca3 b11b466 1687ca3 b11b466 5635c8f b11b466 5635c8f b11b466 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 |
import openai
import gradio as gr
import fitz # PyMuPDF
from openai import OpenAI
import os
import tempfile
import traceback
# 全域變數
api_key = ""
selected_model = "gpt-4"
summary_text = ""
client = None
pdf_text = ""
def set_api_key(user_api_key):
"""設定 OpenAI API Key 並初始化客戶端"""
global api_key, client
try:
api_key = user_api_key.strip()
if not api_key:
return "❌ API Key 不能為空"
client = OpenAI(api_key=api_key)
# 測試 API Key 是否有效
test_response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "你好"}],
max_tokens=5
)
return "✅ API Key 已設定並驗證成功"
except Exception as e:
return f"❌ API Key 設定失敗: {str(e)}"
def set_model(model_name):
"""設定選擇的模型"""
global selected_model
selected_model = model_name
return f"✅ 模型已選擇:{model_name}"
def extract_pdf_text(file_path):
"""從 PDF 文件中提取文字"""
try:
doc = fitz.open(file_path)
text = ""
for page_num, page in enumerate(doc):
page_text = page.get_text()
if page_text.strip(): # 只添加非空白頁面
text += f"\n--- 第 {page_num + 1} 頁 ---\n"
text += page_text
doc.close()
return text
except Exception as e:
return f"❌ PDF 解析錯誤: {str(e)}"
def generate_summary(pdf_file):
"""從 PDF 內容生成摘要"""
global summary_text, pdf_text
if not client:
return "❌ 請先設定 OpenAI API Key"
if not pdf_file:
return "❌ 請先上傳 PDF 文件"
try:
# 從 PDF 提取文字
pdf_text = extract_pdf_text(pdf_file.name)
if not pdf_text.strip():
return "⚠️ 無法解析 PDF 文字,可能為純圖片 PDF 或空白文件。"
# 檢查文字長度,必要時截斷
max_chars = 8000 # 為系統提示留出空間
if len(pdf_text) > max_chars:
pdf_text_truncated = pdf_text[:max_chars] + "\n\n[文本已截斷,僅顯示前 8000 字符]"
else:
pdf_text_truncated = pdf_text
# 生成摘要
response = client.chat.completions.create(
model=selected_model,
messages=[
{
"role": "system",
"content": """你是一個專業的文檔摘要助手。請將以下 PDF 內容整理為結構化的摘要:
1. 首先提供一個簡短的總體概述
2. 然後按照重要性列出主要重點(使用項目符號)
3. 如果有數據或統計信息,請特別標注
4. 如果有結論或建議,請單獨列出
請用繁體中文回答,保持專業且易於理解的語調。"""
},
{"role": "user", "content": pdf_text_truncated}
],
temperature=0.3
)
summary_text = response.choices[0].message.content
return summary_text
except Exception as e:
error_msg = f"❌ 摘要生成失敗: {str(e)}"
print(f"錯誤詳情: {traceback.format_exc()}")
return error_msg
def ask_question(user_question):
"""基於 PDF 內容回答問題"""
if not client:
return "❌ 請先設定 OpenAI API Key"
if not summary_text and not pdf_text:
return "❌ 請先生成 PDF 摘要"
if not user_question.strip():
return "❌ 請輸入問題"
try:
# 使用摘要和原始文本來提供更好的上下文
context = f"PDF 摘要:\n{summary_text}\n\n原始內容(部分):\n{pdf_text[:2000]}"
response = client.chat.completions.create(
model=selected_model,
messages=[
{
"role": "system",
"content": f"""你是一個專業的文檔問答助手。請基於提供的 PDF 內容回答用戶問題。
規則:
1. 只根據提供的文檔內容回答
2. 如果文檔中沒有相關信息,請明確說明
3. 引用具體的文檔內容來支持你的回答
4. 用繁體中文回答
5. 保持客觀和準確
文檔內容:
{context}"""
},
{"role": "user", "content": user_question}
],
temperature=0.2
)
return response.choices[0].message.content
except Exception as e:
error_msg = f"❌ 問答生成失敗: {str(e)}"
print(f"錯誤詳情: {traceback.format_exc()}")
return error_msg
def clear_all():
"""清除所有資料"""
global summary_text, pdf_text
summary_text = ""
pdf_text = ""
return "", "", ""
# 創建 Gradio 介面
with gr.Blocks(
theme=gr.themes.Soft(),
title="PDF 摘要助手",
css="""
/* 修復頁面大小問題 */
.gradio-container {
max-width: none !important;
width: 100% !important;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
min-height: 100vh !important;
padding: 0 !important;
margin: 0 !important;
}
/* 主要內容區域 - 修復大小問題 */
.main-content {
background: rgba(255, 255, 255, 0.95) !important;
border-radius: 20px !important;
margin: 20px auto !important;
padding: 30px !important;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1) !important;
backdrop-filter: blur(10px) !important;
max-width: 1400px !important;
width: calc(100% - 40px) !important;
}
/* 標題樣式 */
.main-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
-webkit-background-clip: text !important;
-webkit-text-fill-color: transparent !important;
background-clip: text !important;
text-align: center !important;
font-size: 2.5em !important;
font-weight: bold !important;
margin-bottom: 20px !important;
}
/* 分頁導航 - 修復點擊問題 */
.gradio-tabs {
border-radius: 15px !important;
overflow: hidden !important;
}
.gradio-tabitem {
padding: 25px !important;
background: white !important;
border-radius: 0 0 15px 15px !important;
}
/* 輸入框樣式 - 修復交互問題 */
input[type="text"],
input[type="password"],
textarea {
border: 2px solid #e0e6ff !important;
border-radius: 12px !important;
padding: 15px !important;
font-size: 16px !important;
transition: all 0.3s ease !important;
width: 100% !important;
box-sizing: border-box !important;
}
input[type="text"]:focus,
input[type="password"]:focus,
textarea:focus {
border-color: #667eea !important;
box-shadow: 0 0 20px rgba(102, 126, 234, 0.3) !important;
outline: none !important;
}
/* 按鈕樣式 - 修復點擊問題 */
button,
.gr-button,
input[type="submit"],
input[type="button"] {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
border: none !important;
border-radius: 12px !important;
color: white !important;
font-weight: 600 !important;
padding: 15px 30px !important;
font-size: 16px !important;
transition: all 0.3s ease !important;
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4) !important;
cursor: pointer !important;
pointer-events: auto !important;
z-index: 1000 !important;
position: relative !important;
display: inline-block !important;
min-height: 44px !important;
line-height: normal !important;
}
button:hover,
.gr-button:hover,
input[type="submit"]:hover,
input[type="button"]:hover {
transform: translateY(-2px) !important;
box-shadow: 0 8px 25px rgba(102, 126, 234, 0.6) !important;
background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%) !important;
}
button:active,
.gr-button:active,
input[type="submit"]:active,
input[type="button"]:active {
transform: translateY(0px) !important;
box-shadow: 0 3px 10px rgba(102, 126, 234, 0.4) !important;
}
/* 次要按鈕樣式 */
button[data-testid*="secondary"],
.gr-button.secondary,
button.secondary {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
}
button[data-testid*="secondary"]:hover,
.gr-button.secondary:hover,
button.secondary:hover {
background: linear-gradient(135deg, #e081e9 0%, #e3455a 100%) !important;
}
/* 修復 Gradio 特定的按鈕容器 */
.gr-form > div,
.gr-button-group,
div[data-testid="button"] {
pointer-events: auto !important;
z-index: 999 !important;
}
/* 確保按鈕內的文字可點擊 */
button span,
.gr-button span {
pointer-events: none !important;
user-select: none !important;
}
/* 文件上傳區域 */
.file-upload-area {
border: 3px dashed #667eea !important;
border-radius: 15px !important;
background: rgba(102, 126, 234, 0.05) !important;
padding: 40px !important;
text-align: center !important;
transition: all 0.3s ease !important;
min-height: 120px !important;
}
.file-upload-area:hover {
background: rgba(102, 126, 234, 0.1) !important;
border-color: #764ba2 !important;
}
/* 單選按鈕容器 */
.radio-group {
background: rgba(102, 126, 234, 0.05) !important;
border-radius: 12px !important;
padding: 20px !important;
margin: 10px 0 !important;
}
/* 輸出文本區域 */
.output-text {
background: #f8f9ff !important;
border: 1px solid #e0e6ff !important;
border-radius: 12px !important;
padding: 20px !important;
min-height: 200px !important;
}
/* 隱藏 Gradio logo 和 footer */
footer,
.gradio-container footer,
div[class*="footer"],
div[class*="Footer"],
.gr-footer {
display: none !important;
}
/* 修復響應式問題 */
.gr-row {
display: flex !important;
gap: 20px !important;
width: 100% !important;
}
.gr-column {
flex: 1 !important;
min-width: 0 !important;
}
/* 確保所有交互元素正常工作 */
* {
pointer-events: auto !important;
}
/* 特殊修復:覆蓋可能的 Gradio 樣式衝突 */
.gradio-container * {
pointer-events: auto !important;
}
/* 修復單選按鈕 */
input[type="radio"] {
pointer-events: auto !important;
cursor: pointer !important;
z-index: 1000 !important;
position: relative !important;
}
/* 修復文件上傳 */
input[type="file"] {
pointer-events: auto !important;
cursor: pointer !important;
z-index: 1000 !important;
}
/* 添加 JavaScript 來確保按鈕響應 */
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
// 確保所有按鈕都可以點擊
function fixButtons() {
const buttons = document.querySelectorAll('button, input[type="submit"], input[type="button"]');
buttons.forEach(btn => {
btn.style.pointerEvents = 'auto';
btn.style.cursor = 'pointer';
btn.style.zIndex = '1000';
btn.style.position = 'relative';
});
}
// 初始修復
fixButtons();
// 定期檢查並修復新出現的按鈕
setInterval(fixButtons, 1000);
// 監聽 DOM 變化
const observer = new MutationObserver(fixButtons);
observer.observe(document.body, {
childList: true,
subtree: true
});
});
</script>
<style>
/* 響應式設計 */
@media (max-width: 768px) {
.main-content {
margin: 10px !important;
padding: 20px !important;
width: calc(100% - 20px) !important;
}
.main-header {
font-size: 1.8em !important;
}
.gr-row {
flex-direction: column !important;
}
button {
width: 100% !important;
margin: 5px 0 !important;
}
}
"""
) as demo:
with gr.Column(elem_classes="main-content"):
gr.HTML("""
<div class="main-header">📄 PDF 摘要 & 問答助手</div>
<div style="text-align: center; margin-bottom: 30px; padding: 25px; background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%); border-radius: 15px; border-left: 5px solid #667eea;">
<h3 style="color: #667eea; margin-bottom: 15px;">🚀 歡迎使用 PDF 智能分析工具!</h3>
<div style="display: flex; justify-content: space-around; flex-wrap: wrap; margin: 20px 0;">
<div style="margin: 10px; padding: 15px; background: white; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.1); min-width: 200px;">
<div style="font-size: 24px; margin-bottom: 10px;">📋</div>
<strong>智能摘要生成</strong><br>
<span style="color: #666;">自動分析 PDF 內容並生成結構化摘要</span>
</div>
<div style="margin: 10px; padding: 15px; background: white; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.1); min-width: 200px;">
<div style="font-size: 24px; margin-bottom: 10px;">🤖</div>
<strong>AI 問答系統</strong><br>
<span style="color: #666;">基於文檔內容回答您的問題</span>
</div>
<div style="margin: 10px; padding: 15px; background: white; border-radius: 10px; box-shadow: 0 3px 10px rgba(0,0,0,0.1); min-width: 200px;">
<div style="font-size: 24px; margin-bottom: 10px;">💡</div>
<strong>快速理解</strong><br>
<span style="color: #666;">快速掌握長篇文檔的核心內容</span>
</div>
</div>
<div style="background: rgba(255, 193, 7, 0.1); padding: 15px; border-radius: 10px; border-left: 4px solid #ffc107; margin-top: 20px;">
<strong style="color: #e65100;">⚠️ 重要提醒:</strong> 使用前請先在「🔧 設定」頁面輸入您的 OpenAI API Key
</div>
</div>
""")
with gr.Tab("🔧 設定", elem_classes="settings-tab"):
gr.Markdown("### ⚙️ 基本設定")
with gr.Row():
with gr.Column():
api_key_input = gr.Textbox(
label="🔑 輸入 OpenAI API Key",
type="password",
placeholder="請輸入您的 OpenAI API Key (sk-...)",
elem_classes="api-input"
)
api_key_status = gr.Textbox(
label="📊 API 連接狀態",
interactive=False,
value="🔄 等待設定 API Key...",
elem_classes="status-display"
)
with gr.Column():
model_choice = gr.Radio(
["gpt-4", "gpt-4.1", "gpt-4.5"],
label="🤖 選擇 AI 模型",
value="gpt-4",
elem_classes="model-selector"
)
model_status = gr.Textbox(
label="🎯 當前模型",
interactive=False,
value="✅ 已選擇:gpt-4",
elem_classes="status-display"
)
# 添加測試按鈕
gr.HTML("<div style='margin: 20px 0; padding: 15px; background: rgba(102, 126, 234, 0.1); border-radius: 10px;'><strong>💡 提示:</strong> 設定完成後,請前往「PDF 處理」頁面上傳文件開始使用!</div>")
with gr.Tab("📄 PDF 處理", elem_classes="pdf-tab"):
gr.Markdown("### 📁 文件上傳與摘要生成")
with gr.Row():
with gr.Column():
pdf_upload = gr.File(
label="📎 選擇 PDF 文件",
file_types=[".pdf"],
elem_classes="file-upload"
)
gr.Markdown("**支援格式**:PDF 文件 (建議 < 10MB)")
with gr.Row():
summary_btn = gr.Button(
"🔄 開始生成摘要",
variant="primary",
elem_classes="primary-btn"
)
clear_btn = gr.Button(
"🗑️ 清除所有資料",
variant="secondary",
elem_classes="secondary-btn"
)
with gr.Column():
summary_output = gr.Textbox(
label="📋 AI 生成的文檔摘要",
lines=15,
placeholder="📄 上傳 PDF 文件並點擊「開始生成摘要」按鈕,AI 將為您分析文檔內容...",
elem_classes="summary-output"
)
with gr.Tab("❓ 智能問答", elem_classes="qa-tab"):
gr.Markdown("### 💬 基於文檔內容的 AI 問答")
with gr.Row():
with gr.Column():
question_input = gr.Textbox(
label="💭 請輸入您的問題",
placeholder="例如:這份文件的主要結論是什麼?文中提到的關鍵數據有哪些?",
lines=3,
elem_classes="question-input"
)
question_btn = gr.Button(
"📤 發送問題",
variant="primary",
elem_classes="primary-btn"
)
gr.Markdown("""
**💡 問題範例:**
- 這份文件討論的主要議題是什麼?
- 文中有哪些重要的統計數據?
- 作者的主要觀點和結論是什麼?
- 文件中提到的建議有哪些?
""")
with gr.Column():
answer_output = gr.Textbox(
label="🤖 AI 智能回答",
lines=12,
placeholder="🤖 請先上傳並生成 PDF 摘要,然後在左側輸入問題,AI 將基於文檔內容為您提供詳細回答...",
elem_classes="answer-output"
)
# 事件處理器
api_key_input.submit(set_api_key, inputs=api_key_input, outputs=api_key_status)
model_choice.change(set_model, inputs=model_choice, outputs=model_status)
summary_btn.click(generate_summary, inputs=pdf_upload, outputs=summary_output)
question_btn.click(ask_question, inputs=question_input, outputs=answer_output)
question_input.submit(ask_question, inputs=question_input, outputs=answer_output)
clear_btn.click(clear_all, outputs=[summary_output, question_input, answer_output])
if __name__ == "__main__":
# Hugging Face Spaces 部署設定
demo.launch(
share=False, # Hugging Face Spaces 不需要 share
show_api=False,
show_error=True
) |