Alexend commited on
Commit
8f2ff91
·
verified ·
1 Parent(s): 0b3967b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -23
app.py CHANGED
@@ -1,29 +1,58 @@
 
 
 
 
1
  import gradio as gr
2
- from transformers import AutoModelForCausalLM, AutoTokenizer
3
- import torch
4
-
5
- # 免費開放模型,不需申請與登入
6
- model_name = "tiiuae/falcon-7b-instruct"
7
-
8
- # 載入 tokenizer 與模型
9
- tokenizer = AutoTokenizer.from_pretrained(model_name)
10
- model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, device_map="auto")
11
-
12
- # 對話函數
13
- def chat(user_input):
14
- prompt = f"{user_input}"
15
- inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
16
- outputs = model.generate(**inputs, max_new_tokens=256, do_sample=True, top_p=0.95, temperature=0.7)
17
- result = tokenizer.decode(outputs[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  return result.strip()
19
 
20
- # Gradio UI 介面
21
- gr.Interface(
22
- fn=chat,
23
- inputs=gr.Textbox(lines=2, placeholder="請問有關南臺科技大學的問題...", label="輸入問題"),
 
 
 
 
 
 
 
 
 
 
24
  outputs="text",
25
- title="南臺科技大學 問答機器人",
26
- description="免費 GPT 替代模型(Falcon 7B Instruct)不需 API 金鑰或登入。",
27
  theme="default"
28
- ).launch()
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()