Update app.py
Browse files
app.py
CHANGED
|
@@ -1,29 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from transformers import
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
return result.strip()
|
| 19 |
|
| 20 |
-
#
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
outputs="text",
|
| 25 |
-
title="南臺科技大學 問答機器人",
|
| 26 |
-
description="
|
| 27 |
theme="default"
|
| 28 |
-
)
|
| 29 |
|
|
|
|
|
|
| 1 |
+
# ✅ Hugging Face + 小型模型 + QA.json + 本地爬蟲資料庫 fallback
|
| 2 |
+
# 檔名:app.py(Hugging Face Spaces 專用)
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
import gradio as gr
|
| 6 |
+
from transformers import pipeline
|
| 7 |
+
|
| 8 |
+
# ✅ 小型模型
|
| 9 |
+
qa_model = pipeline("text2text-generation", model="google/flan-t5-base")
|
| 10 |
+
|
| 11 |
+
# ✅ 載入 QA.json
|
| 12 |
+
with open("qa.json", "r", encoding="utf-8") as f:
|
| 13 |
+
qa_data = json.load(f)
|
| 14 |
+
|
| 15 |
+
# ✅ 載入爬下來的文字資料(取代即時爬蟲)
|
| 16 |
+
with open("web_content.txt", "r", encoding="utf-8") as f:
|
| 17 |
+
web_data = f.read()
|
| 18 |
+
|
| 19 |
+
# ✅ 查詢 QA.json 資料
|
| 20 |
+
|
| 21 |
+
def retrieve_qa_context(user_input):
|
| 22 |
+
for item in qa_data:
|
| 23 |
+
if item["match"] == "OR":
|
| 24 |
+
if any(k in user_input for k in item["keywords"]):
|
| 25 |
+
return item["response"]
|
| 26 |
+
elif item["match"] == "AND":
|
| 27 |
+
if all(k in user_input for k in item["keywords"]):
|
| 28 |
+
return item["response"]
|
| 29 |
+
return None
|
| 30 |
+
|
| 31 |
+
# ✅ GPT 模型生成人性化回答
|
| 32 |
+
|
| 33 |
+
def generate_answer_from_context(user_input, context):
|
| 34 |
+
prompt = f"根據以下資料,用繁體中文、口語化並簡潔地回答這個問題:\n\n[資料內容]\n{context}\n\n[問題]\n{user_input}\n\n回答:"
|
| 35 |
+
result = qa_model(prompt, max_new_tokens=100)[0]['generated_text']
|
| 36 |
return result.strip()
|
| 37 |
|
| 38 |
+
# ✅ 主回答流程
|
| 39 |
+
|
| 40 |
+
def answer(user_input):
|
| 41 |
+
context = retrieve_qa_context(user_input)
|
| 42 |
+
if context:
|
| 43 |
+
return generate_answer_from_context(user_input, context)
|
| 44 |
+
else:
|
| 45 |
+
# fallback: 使用本地爬蟲資料庫 web_content.txt
|
| 46 |
+
return generate_answer_from_context(user_input, web_data)
|
| 47 |
+
|
| 48 |
+
# ✅ Gradio UI 介面
|
| 49 |
+
interface = gr.Interface(
|
| 50 |
+
fn=answer,
|
| 51 |
+
inputs=gr.Textbox(lines=2, placeholder="請問有關南臺科技大學的問題..."),
|
| 52 |
outputs="text",
|
| 53 |
+
title="南臺科技大學 問答機器人 (小模型 + 本地知識庫)",
|
| 54 |
+
description="先比對內建資料庫,再用爬蟲資料庫生成答案。支援人性化口語回覆。",
|
| 55 |
theme="default"
|
| 56 |
+
)
|
| 57 |
|
| 58 |
+
interface.launch()
|