Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import openai
|
| 3 |
+
import fitz # PyMuPDF
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# ✅ 使用環境變數來安全存取 OpenAI API Key
|
| 9 |
+
openai_key = os.getenv("OPENAI_API_KEY")
|
| 10 |
+
if not openai_key:
|
| 11 |
+
raise ValueError("API Key 未設置,請確保已設定環境變數 OPENAI_API_KEY")
|
| 12 |
+
|
| 13 |
+
# ✅ PDF 檔案名稱(將 PDF 上傳到 Space 目錄)
|
| 14 |
+
PDF_FILE = "statistics.pdf"
|
| 15 |
+
|
| 16 |
+
# ✅ 萃取 PDF 內容
|
| 17 |
+
def extract_text_from_pdf(pdf_path):
|
| 18 |
+
try:
|
| 19 |
+
doc = fitz.open(pdf_path)
|
| 20 |
+
text = ""
|
| 21 |
+
for page in doc:
|
| 22 |
+
text += page.get_text()
|
| 23 |
+
print(f"✅ 成功讀取 {pdf_path}")
|
| 24 |
+
return text
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"❌ PDF 解析錯誤: {e}")
|
| 27 |
+
return ""
|
| 28 |
+
|
| 29 |
+
# ✅ 嘗試載入 PDF 內容
|
| 30 |
+
if os.path.exists(PDF_FILE):
|
| 31 |
+
content = extract_text_from_pdf(PDF_FILE)
|
| 32 |
+
else:
|
| 33 |
+
print(f"⚠️ 找不到 {PDF_FILE},請將 PDF 上傳到 Space。")
|
| 34 |
+
content = ""
|
| 35 |
+
|
| 36 |
+
# ✅ 調用 OpenAI API
|
| 37 |
+
def openai_api(messages, openai_key):
|
| 38 |
+
try:
|
| 39 |
+
client = openai.OpenAI(api_key=openai_key)
|
| 40 |
+
completion = client.chat.completions.create(
|
| 41 |
+
model="gpt-4o",
|
| 42 |
+
messages=messages
|
| 43 |
+
)
|
| 44 |
+
if not completion or not completion.choices:
|
| 45 |
+
return "API 沒有回應,請檢查 API Key 或伺服器狀態。"
|
| 46 |
+
response = completion.choices[0].message.content
|
| 47 |
+
return response
|
| 48 |
+
except Exception as e:
|
| 49 |
+
return f"API 呼叫發生錯誤:{str(e)}"
|
| 50 |
+
|
| 51 |
+
# ✅ 準備對話訊息
|
| 52 |
+
def predict(inputs, chatbot):
|
| 53 |
+
messages = []
|
| 54 |
+
system_prompt = {
|
| 55 |
+
"role": "system",
|
| 56 |
+
"content": f"請扮演助教機器人,針對我所上傳的『統計學』PDF 文件進行問答。以下是學習內容:\n\n{content}"
|
| 57 |
+
}
|
| 58 |
+
messages.append(system_prompt)
|
| 59 |
+
|
| 60 |
+
if chatbot is None:
|
| 61 |
+
chatbot = []
|
| 62 |
+
|
| 63 |
+
for conv in chatbot:
|
| 64 |
+
if isinstance(conv, dict) and "role" in conv and "content" in conv:
|
| 65 |
+
messages.append({"role": conv["role"], "content": conv["content"]})
|
| 66 |
+
|
| 67 |
+
messages.append({"role": "user", "content": inputs})
|
| 68 |
+
return messages
|
| 69 |
+
|
| 70 |
+
# ✅ 逐字輸出訊息
|
| 71 |
+
def slow_echo(inputs, chatbot):
|
| 72 |
+
messages = predict(inputs, chatbot)
|
| 73 |
+
re_message = openai_api(messages, openai_key)
|
| 74 |
+
|
| 75 |
+
if not re_message:
|
| 76 |
+
re_message = "無法取得回應,請稍後再試。"
|
| 77 |
+
|
| 78 |
+
for i in range(len(re_message)):
|
| 79 |
+
yield re_message[: i + 1]
|
| 80 |
+
time.sleep(0.05)
|
| 81 |
+
|
| 82 |
+
# ✅ 建立 Gradio 介面
|
| 83 |
+
def setup_gradio_interface():
|
| 84 |
+
demo = gr.ChatInterface(
|
| 85 |
+
slow_echo,
|
| 86 |
+
chatbot=gr.Chatbot(height=500, type="messages"), # ✅ 修正 type 參數
|
| 87 |
+
title="📊 統計學助教機器人",
|
| 88 |
+
description="請輸入與統計學有關的問題,機器人將基於所上傳的 PDF 內容來回答。"
|
| 89 |
+
)
|
| 90 |
+
return demo
|
| 91 |
+
|
| 92 |
+
# ✅ 啟動應用程式
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
demo = setup_gradio_interface()
|
| 95 |
+
port = int(os.environ.get("PORT", 7860))
|
| 96 |
+
demo.queue()
|
| 97 |
+
#demo.launch(server_name="0.0.0.0", server_port=port)
|
| 98 |
+
demo.launch()
|