Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,6 +4,7 @@ import fitz
|
|
4 |
from openai import OpenAI
|
5 |
import traceback
|
6 |
|
|
|
7 |
api_key = ""
|
8 |
selected_model = "gpt-4"
|
9 |
summary_text = ""
|
@@ -11,27 +12,41 @@ client = None
|
|
11 |
pdf_text = ""
|
12 |
|
13 |
def set_api_key(user_api_key):
|
|
|
14 |
global api_key, client
|
15 |
try:
|
16 |
api_key = user_api_key.strip()
|
17 |
if not api_key:
|
18 |
return "❌ API Key 不能為空"
|
|
|
|
|
|
|
|
|
19 |
client = OpenAI(api_key=api_key)
|
20 |
-
|
21 |
-
|
22 |
-
|
|
|
|
|
23 |
max_tokens=5
|
24 |
)
|
25 |
-
return "✅ API Key
|
26 |
except Exception as e:
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
28 |
|
29 |
def set_model(model_name):
|
|
|
30 |
global selected_model
|
31 |
selected_model = model_name
|
32 |
return f"✅ 模型已選擇:{model_name}"
|
33 |
|
34 |
def extract_pdf_text(file_path):
|
|
|
35 |
try:
|
36 |
doc = fitz.open(file_path)
|
37 |
text = ""
|
@@ -45,86 +60,218 @@ def extract_pdf_text(file_path):
|
|
45 |
return f"❌ PDF 解析錯誤: {str(e)}"
|
46 |
|
47 |
def generate_summary(pdf_file):
|
|
|
48 |
global summary_text, pdf_text
|
|
|
49 |
if not client:
|
50 |
return "❌ 請先設定 OpenAI API Key"
|
|
|
51 |
if not pdf_file:
|
52 |
return "❌ 請先上傳 PDF 文件"
|
|
|
53 |
try:
|
|
|
54 |
pdf_text = extract_pdf_text(pdf_file.name)
|
|
|
55 |
if not pdf_text.strip():
|
56 |
return "⚠️ 無法解析 PDF 文字,可能為純圖片 PDF 或空白文件。"
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
response = client.chat.completions.create(
|
59 |
model=selected_model,
|
60 |
messages=[
|
61 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
{"role": "user", "content": pdf_text_truncated}
|
63 |
],
|
64 |
temperature=0.3
|
65 |
)
|
|
|
66 |
summary_text = response.choices[0].message.content
|
67 |
return summary_text
|
|
|
68 |
except Exception as e:
|
69 |
-
print(traceback.format_exc())
|
70 |
return f"❌ 摘要生成失敗: {str(e)}"
|
71 |
|
72 |
def ask_question(user_question):
|
|
|
73 |
if not client:
|
74 |
return "❌ 請先設定 OpenAI API Key"
|
|
|
75 |
if not summary_text and not pdf_text:
|
76 |
return "❌ 請先生成 PDF 摘要"
|
|
|
77 |
if not user_question.strip():
|
78 |
return "❌ 請輸入問題"
|
|
|
79 |
try:
|
|
|
80 |
context = f"PDF 摘要:\n{summary_text}\n\n原始內容(部分):\n{pdf_text[:2000]}"
|
|
|
81 |
response = client.chat.completions.create(
|
82 |
model=selected_model,
|
83 |
messages=[
|
84 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
85 |
{"role": "user", "content": user_question}
|
86 |
],
|
87 |
temperature=0.2
|
88 |
)
|
|
|
89 |
return response.choices[0].message.content
|
|
|
90 |
except Exception as e:
|
91 |
-
print(traceback.format_exc())
|
92 |
return f"❌ 問答生成失敗: {str(e)}"
|
93 |
|
94 |
def clear_all():
|
|
|
95 |
global summary_text, pdf_text
|
96 |
summary_text = ""
|
97 |
pdf_text = ""
|
98 |
return "", "", ""
|
99 |
|
100 |
-
|
101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
with gr.Tab("🔧 設定"):
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
127 |
clear_btn.click(clear_all, outputs=[summary_output, question_input, answer_output])
|
128 |
|
129 |
if __name__ == "__main__":
|
130 |
-
demo.launch(
|
|
|
|
|
|
|
|
4 |
from openai import OpenAI
|
5 |
import traceback
|
6 |
|
7 |
+
# 全域變數
|
8 |
api_key = ""
|
9 |
selected_model = "gpt-4"
|
10 |
summary_text = ""
|
|
|
12 |
pdf_text = ""
|
13 |
|
14 |
def set_api_key(user_api_key):
|
15 |
+
"""設定 OpenAI API Key 並初始化客戶端"""
|
16 |
global api_key, client
|
17 |
try:
|
18 |
api_key = user_api_key.strip()
|
19 |
if not api_key:
|
20 |
return "❌ API Key 不能為空"
|
21 |
+
|
22 |
+
if not api_key.startswith('sk-'):
|
23 |
+
return "❌ API Key 格式錯誤,應該以 'sk-' 開頭"
|
24 |
+
|
25 |
client = OpenAI(api_key=api_key)
|
26 |
+
|
27 |
+
# 測試 API Key 是否有效
|
28 |
+
test_response = client.chat.completions.create(
|
29 |
+
model="gpt-3.5-turbo", # 使用較便宜的模型測試
|
30 |
+
messages=[{"role": "user", "content": "測試"}],
|
31 |
max_tokens=5
|
32 |
)
|
33 |
+
return "✅ API Key 已設定並驗證成功!"
|
34 |
except Exception as e:
|
35 |
+
if "incorrect_api_key" in str(e).lower():
|
36 |
+
return "❌ API Key 無效,請檢查是否正確"
|
37 |
+
elif "quota" in str(e).lower():
|
38 |
+
return "⚠️ API Key 有效,但配額不足"
|
39 |
+
else:
|
40 |
+
return f"❌ API Key 設定失敗: {str(e)}"
|
41 |
|
42 |
def set_model(model_name):
|
43 |
+
"""設定選擇的模型"""
|
44 |
global selected_model
|
45 |
selected_model = model_name
|
46 |
return f"✅ 模型已選擇:{model_name}"
|
47 |
|
48 |
def extract_pdf_text(file_path):
|
49 |
+
"""從 PDF 文件中提取文字"""
|
50 |
try:
|
51 |
doc = fitz.open(file_path)
|
52 |
text = ""
|
|
|
60 |
return f"❌ PDF 解析錯誤: {str(e)}"
|
61 |
|
62 |
def generate_summary(pdf_file):
|
63 |
+
"""從 PDF 內容生成摘要"""
|
64 |
global summary_text, pdf_text
|
65 |
+
|
66 |
if not client:
|
67 |
return "❌ 請先設定 OpenAI API Key"
|
68 |
+
|
69 |
if not pdf_file:
|
70 |
return "❌ 請先上傳 PDF 文件"
|
71 |
+
|
72 |
try:
|
73 |
+
# 從 PDF 提取文字
|
74 |
pdf_text = extract_pdf_text(pdf_file.name)
|
75 |
+
|
76 |
if not pdf_text.strip():
|
77 |
return "⚠️ 無法解析 PDF 文字,可能為純圖片 PDF 或空白文件。"
|
78 |
+
|
79 |
+
# 截斷過長的文字
|
80 |
+
max_chars = 8000
|
81 |
+
if len(pdf_text) > max_chars:
|
82 |
+
pdf_text_truncated = pdf_text[:max_chars] + "\n\n[文本已截斷,僅顯示前 8000 字符]"
|
83 |
+
else:
|
84 |
+
pdf_text_truncated = pdf_text
|
85 |
+
|
86 |
+
# 生成摘要
|
87 |
response = client.chat.completions.create(
|
88 |
model=selected_model,
|
89 |
messages=[
|
90 |
+
{
|
91 |
+
"role": "system",
|
92 |
+
"content": """你是一個專業的文檔摘要助手。請將以下 PDF 內容整理為結構化的摘要:
|
93 |
+
|
94 |
+
1. 首先提供一個簡短的總體概述
|
95 |
+
2. 然後按照重要性列出主要重點(使用項目符號)
|
96 |
+
3. 如果有數據或統計信息,請特別標注
|
97 |
+
4. 如果有結論或建議,請單獨列出
|
98 |
+
|
99 |
+
請用繁體中文回答,保持專業且易於理解的語調。"""
|
100 |
+
},
|
101 |
{"role": "user", "content": pdf_text_truncated}
|
102 |
],
|
103 |
temperature=0.3
|
104 |
)
|
105 |
+
|
106 |
summary_text = response.choices[0].message.content
|
107 |
return summary_text
|
108 |
+
|
109 |
except Exception as e:
|
110 |
+
print(f"錯誤詳情: {traceback.format_exc()}")
|
111 |
return f"❌ 摘要生成失敗: {str(e)}"
|
112 |
|
113 |
def ask_question(user_question):
|
114 |
+
"""基於 PDF 內容回答問題"""
|
115 |
if not client:
|
116 |
return "❌ 請先設定 OpenAI API Key"
|
117 |
+
|
118 |
if not summary_text and not pdf_text:
|
119 |
return "❌ 請先生成 PDF 摘要"
|
120 |
+
|
121 |
if not user_question.strip():
|
122 |
return "❌ 請輸入問題"
|
123 |
+
|
124 |
try:
|
125 |
+
# 組合上下文
|
126 |
context = f"PDF 摘要:\n{summary_text}\n\n原始內容(部分):\n{pdf_text[:2000]}"
|
127 |
+
|
128 |
response = client.chat.completions.create(
|
129 |
model=selected_model,
|
130 |
messages=[
|
131 |
+
{
|
132 |
+
"role": "system",
|
133 |
+
"content": f"""你是一個專業的文檔問答助手。請基於提供的 PDF 內容回答用戶問題。
|
134 |
+
|
135 |
+
規則:
|
136 |
+
1. 只根據提供的文檔內容回答
|
137 |
+
2. 如果文檔中沒有相關信息,請明確說明
|
138 |
+
3. 引用具體的文檔內容來支持你的回答
|
139 |
+
4. 用繁體中文回答
|
140 |
+
5. 保持客觀和準確
|
141 |
+
|
142 |
+
文檔內容:
|
143 |
+
{context}"""
|
144 |
+
},
|
145 |
{"role": "user", "content": user_question}
|
146 |
],
|
147 |
temperature=0.2
|
148 |
)
|
149 |
+
|
150 |
return response.choices[0].message.content
|
151 |
+
|
152 |
except Exception as e:
|
153 |
+
print(f"錯誤詳情: {traceback.format_exc()}")
|
154 |
return f"❌ 問答生成失敗: {str(e)}"
|
155 |
|
156 |
def clear_all():
|
157 |
+
"""清除所有資料"""
|
158 |
global summary_text, pdf_text
|
159 |
summary_text = ""
|
160 |
pdf_text = ""
|
161 |
return "", "", ""
|
162 |
|
163 |
+
# 創建 Gradio 介面
|
164 |
+
with gr.Blocks(
|
165 |
+
title="PDF 摘要助手",
|
166 |
+
css="""
|
167 |
+
/* 隱藏 Gradio footer 和 logo */
|
168 |
+
footer { display: none !important; }
|
169 |
+
.gradio-container footer { display: none !important; }
|
170 |
+
div[class*="footer"] { display: none !important; }
|
171 |
+
div[class*="Footer"] { display: none !important; }
|
172 |
+
.gr-footer { display: none !important; }
|
173 |
+
"""
|
174 |
+
) as demo:
|
175 |
+
|
176 |
+
gr.Markdown("""
|
177 |
+
# 📄 PDF 摘要 & 問答助手
|
178 |
+
|
179 |
+
🚀 **歡迎使用 PDF 智能分析工具!**
|
180 |
+
|
181 |
+
**主要功能:**
|
182 |
+
- 📋 自動生成 PDF 文檔摘要
|
183 |
+
- 🤖 基於文檔內容回答問題
|
184 |
+
- 💡 快速理解長篇文檔的核心內容
|
185 |
+
|
186 |
+
**使用步驟:**
|
187 |
+
1. 先在「設定」頁面輸入您的 OpenAI API Key
|
188 |
+
2. 選擇適合的 AI 模型
|
189 |
+
3. 在「摘要」頁面上傳 PDF 文件並生成摘要
|
190 |
+
4. 在「問答」頁面提出關於文件的問題
|
191 |
+
|
192 |
+
---
|
193 |
+
""")
|
194 |
|
195 |
with gr.Tab("🔧 設定"):
|
196 |
+
gr.Markdown("### API Key 設定")
|
197 |
+
api_key_input = gr.Textbox(
|
198 |
+
label="🔑 輸入 OpenAI API Key",
|
199 |
+
type="password",
|
200 |
+
placeholder="請輸入您的 OpenAI API Key (sk-...)"
|
201 |
+
)
|
202 |
+
api_key_btn = gr.Button("確認 API Key", variant="primary")
|
203 |
+
api_key_status = gr.Textbox(
|
204 |
+
label="📊 API 狀態",
|
205 |
+
interactive=False,
|
206 |
+
value="🔄 等待設定 API Key..."
|
207 |
+
)
|
208 |
+
|
209 |
+
gr.Markdown("### 模型選擇")
|
210 |
+
model_choice = gr.Radio(
|
211 |
+
["gpt-4", "gpt-4.1", "gpt-4.5"],
|
212 |
+
label="🤖 選擇 AI 模型",
|
213 |
+
value="gpt-4"
|
214 |
+
)
|
215 |
+
model_status = gr.Textbox(
|
216 |
+
label="🎯 模型狀態",
|
217 |
+
interactive=False,
|
218 |
+
value="✅ 已選擇:gpt-4"
|
219 |
+
)
|
220 |
+
|
221 |
+
with gr.Tab("📄 PDF 摘要"):
|
222 |
+
gr.Markdown("### 文件上傳與摘要生成")
|
223 |
+
pdf_upload = gr.File(
|
224 |
+
label="📁 上傳 PDF 文件",
|
225 |
+
file_types=[".pdf"]
|
226 |
+
)
|
227 |
+
with gr.Row():
|
228 |
+
summary_btn = gr.Button("🔄 生成摘要", variant="primary")
|
229 |
+
clear_btn = gr.Button("🗑️ 清除資料", variant="secondary")
|
230 |
+
|
231 |
+
summary_output = gr.Textbox(
|
232 |
+
label="📋 PDF 摘要",
|
233 |
+
lines=15,
|
234 |
+
placeholder="上傳 PDF 文件並點擊「生成摘要」按鈕,AI 將為您分析文檔內容..."
|
235 |
+
)
|
236 |
+
|
237 |
+
with gr.Tab("❓ 智能問答"):
|
238 |
+
gr.Markdown("### 基於文檔內容的問答")
|
239 |
+
question_input = gr.Textbox(
|
240 |
+
label="💭 請輸入您的問題",
|
241 |
+
lines=3,
|
242 |
+
placeholder="例如:這份文件的主要結論是什麼?文中提到的關鍵數據有哪些?"
|
243 |
+
)
|
244 |
+
question_btn = gr.Button("📤 送出問題", variant="primary")
|
245 |
+
|
246 |
+
answer_output = gr.Textbox(
|
247 |
+
label="🤖 AI 回答",
|
248 |
+
lines=12,
|
249 |
+
placeholder="請先上傳並生成 PDF 摘要,然後輸入問題,AI 將基於文檔內容為您���供回答..."
|
250 |
+
)
|
251 |
+
|
252 |
+
gr.Markdown("""
|
253 |
+
**💡 問題範例:**
|
254 |
+
- 這份文件討論的主要議題是什麼?
|
255 |
+
- 文中有哪些重要的統計數據?
|
256 |
+
- 作者的主要觀點和結論是什麼?
|
257 |
+
- 文件中提到的建議有哪些?
|
258 |
+
""")
|
259 |
+
|
260 |
+
# 事件綁定 - 保持原有的簡單方式
|
261 |
+
api_key_btn.click(set_api_key, inputs=api_key_input, outputs=api_key_status)
|
262 |
+
api_key_input.submit(set_api_key, inputs=api_key_input, outputs=api_key_status)
|
263 |
+
|
264 |
+
model_choice.change(set_model, inputs=model_choice, outputs=model_status)
|
265 |
+
|
266 |
+
summary_btn.click(generate_summary, inputs=pdf_upload, outputs=summary_output)
|
267 |
+
|
268 |
+
question_btn.click(ask_question, inputs=question_input, outputs=answer_output)
|
269 |
+
question_input.submit(ask_question, inputs=question_input, outputs=answer_output)
|
270 |
+
|
271 |
clear_btn.click(clear_all, outputs=[summary_output, question_input, answer_output])
|
272 |
|
273 |
if __name__ == "__main__":
|
274 |
+
demo.launch(
|
275 |
+
show_error=True,
|
276 |
+
share=False
|
277 |
+
)
|