File size: 4,485 Bytes
8f7234f
d051231
 
 
 
 
c4310e4
d051231
 
 
1740855
8f7234f
d051231
8f7234f
9c1b3ba
d051231
 
 
 
 
8f7234f
c4310e4
 
 
 
d051231
06f5c87
 
 
 
 
 
 
8f7234f
06f5c87
c4310e4
d051231
 
8f7234f
d051231
 
 
 
 
 
 
8f7234f
 
 
d051231
 
 
06f5c87
c4310e4
d051231
 
 
 
 
 
8f7234f
06f5c87
 
 
 
 
 
 
 
 
8f7234f
 
 
 
06f5c87
 
 
d0ba755
8f7234f
d0ba755
 
 
 
 
6f0de2e
8f7234f
 
 
 
 
 
80fe36a
06f5c87
6f0de2e
8f7234f
06f5c87
 
6f0de2e
a23ab36
132ef2d
06f5c87
6f0de2e
06f5c87
6f0de2e
06f5c87
 
80fe36a
d0ba755
06f5c87
d0ba755
c6f8f84
06f5c87
c6f8f84
8f7234f
fb13185
c6f8f84
8f7234f
d0ba755
f90da5a
255d19f
06f5c87
a23ab36
8f7234f
255d19f
f90da5a
d0ba755
a6c8097
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import os, torch
from langchain.docstore.document import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import FAISS
from langchain_huggingface import HuggingFaceEmbeddings
from docx import Document as DocxDocument
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
from huggingface_hub import login, snapshot_download
import gradio as gr

# -------------------------------
# 1. 模型設定(中文 T5)
# -------------------------------
MODEL_NAME = "Langboat/mengzi-t5-base"   # ✅ 換成穩定的中文 T5

HF_TOKEN = os.environ.get("HUGGINGFACEHUB_API_TOKEN")
if HF_TOKEN:
    login(token=HF_TOKEN)
    print("✅ 已使用 HUGGINGFACEHUB_API_TOKEN 登入 Hugging Face")

# 嘗試下載模型
LOCAL_MODEL_DIR = f"./models/{MODEL_NAME.split('/')[-1]}"
if not os.path.exists(LOCAL_MODEL_DIR):
    print(f"⬇️ 嘗試下載模型 {MODEL_NAME} ...")
    snapshot_download(repo_id=MODEL_NAME, token=HF_TOKEN, local_dir=LOCAL_MODEL_DIR)

print(f"👉 最終使用模型:{MODEL_NAME}")

# -------------------------------
# 2. pipeline 載入
# -------------------------------
tokenizer = AutoTokenizer.from_pretrained(
    LOCAL_MODEL_DIR,
    use_fast=False   # ✅ 避免 tiktoken / fast tokenizer 問題
)
model = AutoModelForSeq2SeqLM.from_pretrained(LOCAL_MODEL_DIR)

generator = pipeline(
    "text2text-generation",  # ✅ Seq2Seq 用這個
    model=model,
    tokenizer=tokenizer,
    device=-1  # CPU
)

def call_local_inference(prompt, max_new_tokens=256):
    try:
        if "中文" not in prompt:
            prompt += "\n(請用中文回答)"

        outputs = generator(
            prompt,
            max_new_tokens=max_new_tokens,
            do_sample=True,
            temperature=0.7
        )
        return outputs[0]["generated_text"]
    except Exception as e:
        return f"(生成失敗:{e})"

# -------------------------------
# 3. RAG 部分:向量資料庫
# -------------------------------
DB_PATH = "./faiss_db"
EMBEDDINGS_MODEL_NAME = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
embeddings_model = HuggingFaceEmbeddings(model_name=EMBEDDINGS_MODEL_NAME)

if os.path.exists(os.path.join(DB_PATH, "index.faiss")):
    print("✅ 載入現有向量資料庫...")
    db = FAISS.load_local(DB_PATH, embeddings_model, allow_dangerous_deserialization=True)
else:
    print("⚠️ 沒有找到資料庫,請先建立 faiss_db")
    db = None

retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": 3}) if db else None

# -------------------------------
# 4. 文章生成(結合 RAG)
# -------------------------------
def generate_article_progress(query, segments=3):
    docx_file = "/tmp/generated_article.docx"
    doc = DocxDocument()
    doc.add_heading(query, level=1)

    all_text = []

    # 🔍 從資料庫檢索
    context = ""
    if retriever:
        retrieved_docs = retriever.get_relevant_documents(query)
        context_texts = [d.page_content for d in retrieved_docs]
        context = "\n".join([f"{i+1}. {txt}" for i, txt in enumerate(context_texts[:3])])

    for i in range(segments):
        prompt = (
            f"以下是佛教經論的相關內容:\n{context}\n\n"
            f"請依據上面內容,寫一段約150-200字的中文文章,"
            f"主題:{query}。\n第{i+1}段:"
        )
        paragraph = call_local_inference(prompt)
        all_text.append(paragraph)
        doc.add_paragraph(paragraph)

        yield "\n\n".join(all_text), None, f"本次使用模型:{MODEL_NAME}"

    doc.save(docx_file)
    yield "\n\n".join(all_text), docx_file, f"本次使用模型:{MODEL_NAME}"

# -------------------------------
# 5. Gradio 介面
# -------------------------------
with gr.Blocks() as demo:
    gr.Markdown("# 📺 電視弘法視頻生成文章 RAG 系統")
    query_input = gr.Textbox(lines=2, placeholder="請輸入文章主題", label="文章主題")
    segments_input = gr.Slider(minimum=1, maximum=10, step=1, value=3, label="段落數")
    output_text = gr.Textbox(label="生成文章")
    output_file = gr.File(label="下載 DOCX")
    model_info = gr.Textbox(label="模型資訊")

    btn = gr.Button("生成文章")
    btn.click(
        generate_article_progress,
        inputs=[query_input, segments_input],
        outputs=[output_text, output_file, model_info]
    )

if __name__ == "__main__":
    demo.launch()