Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| from sentence_transformers import SentenceTransformer | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline | |
| import faiss | |
| import numpy as np | |
| import torch | |
| # 1️⃣ 載入文本資料 | |
| with open("data.txt", "r", encoding="utf-8", errors="ignore") as f: | |
| docs = f.readlines() | |
| # 2️⃣ 建立文本向量 | |
| embedder = SentenceTransformer("all-MiniLM-L6-v2") | |
| doc_embeddings = embedder.encode(docs, convert_to_numpy=True) | |
| # 3️⃣ 建立 FAISS 向量索引 | |
| index = faiss.IndexFlatL2(doc_embeddings.shape[1]) | |
| index.add(doc_embeddings) | |
| # 4️⃣ 載入中文生成模型 (CPU 友好版本) | |
| model_name = "Qwen/Qwen2.5-0.5B-Instruct" | |
| tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) | |
| model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True) | |
| generator = pipeline("text-generation", model=model, tokenizer=tokenizer) | |
| # 5️⃣ 定義 RAG 聊天功能 | |
| def rag_chat(question): | |
| # 將使用者問題轉向量 | |
| q_emb = embedder.encode([question], convert_to_numpy=True) | |
| D, I = index.search(q_emb, k=2) # 找出最相關的 2 句 | |
| context = "\n".join([docs[i].strip() for i in I[0]]) | |
| if not context.strip(): | |
| return "我找不到相關資料。" | |
| prompt = f""" | |
| 你是一個知識問答助手。請根據下列提供的資料內容回答問題。 | |
| ⚠️ 如果資料中沒有提到答案,請直接回答「我不知道」。 | |
| 請勿使用你自己的知識或推測。 | |
| 資料: | |
| {context} | |
| 問題:{question} | |
| 請用英文簡潔回答: | |
| """ | |
| output = generator( | |
| prompt, | |
| max_new_tokens=200, | |
| do_sample=True, | |
| temperature=0.5, | |
| top_p=0.9, | |
| repetition_penalty=1.2, | |
| num_return_sequences=1 | |
| )[0]["generated_text"] | |
| answer = output.replace(prompt, "").strip() | |
| return answer | |
| # 6️⃣ 建立 Gradio 介面 | |
| demo = gr.Interface( | |
| fn=rag_chat, | |
| inputs=gr.Textbox(label="輸入你的問題", placeholder="例如:我想了解自己有哪些特質?"), | |
| outputs=gr.Textbox(label="模型回答"), | |
| title="🧠 Temet nosce 認識自己", | |
| description="這個模型會根據提供的文本資料找出相關資訊,並用英文回答,幫助你更認識自己。" | |
| ) | |
| # 直接啟動 Gradio | |
| demo.launch() | |