File size: 4,921 Bytes
058eba2
8f7234f
d051231
 
 
 
 
c4310e4
d051231
 
 
1740855
6d8dd36
d051231
6d8dd36
 
9c1b3ba
d051231
 
 
 
 
058eba2
 
 
 
 
 
 
 
 
 
 
6d8dd36
058eba2
 
6d8dd36
058eba2
 
 
 
d051231
06f5c87
 
 
6d8dd36
06f5c87
6d8dd36
 
d051231
 
6d8dd36
d051231
 
6d8dd36
d051231
 
 
 
 
 
 
06f5c87
c4310e4
d051231
 
 
 
 
 
6d8dd36
06f5c87
 
 
 
6d8dd36
06f5c87
 
 
 
6d8dd36
 
8f7234f
6d8dd36
06f5c87
 
6d8dd36
d0ba755
6d8dd36
d0ba755
 
 
 
 
6f0de2e
6d8dd36
 
 
 
 
80fe36a
06f5c87
6f0de2e
6d8dd36
06f5c87
 
6f0de2e
a23ab36
132ef2d
06f5c87
6d8dd36
6f0de2e
06f5c87
6d8dd36
80fe36a
d0ba755
06f5c87
d0ba755
c6f8f84
06f5c87
6d8dd36
058eba2
c6f8f84
6d8dd36
fb13185
c6f8f84
6d8dd36
d0ba755
f90da5a
255d19f
06f5c87
a23ab36
6d8dd36
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
129
130
131
132
133
134
135
136
137
138
# app.py
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 + fallback)
# -------------------------------
PRIMARY_MODEL = "Langboat/mengzi-t5-base"  # ✅ 帶 spiece.model
FALLBACK_MODEL = "uer/t5-small-chinese-cluecorpussmall"

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

def try_download_model(repo_id):
    local_dir = f"./models/{repo_id.split('/')[-1]}"
    if not os.path.exists(local_dir):
        print(f"⬇️ 嘗試下載模型 {repo_id} ...")
        try:
            snapshot_download(repo_id=repo_id, token=HF_TOKEN, local_dir=local_dir)
        except Exception as e:
            print(f"⚠️ 模型 {repo_id} 無法下載: {e}")
            return None
    return local_dir

# 嘗試下載 Primary,失敗就換 Small
LOCAL_MODEL_DIR = try_download_model(PRIMARY_MODEL)
if LOCAL_MODEL_DIR is None:
    print("⚠️ 切換到 fallback 模型:小型 T5-Chinese")
    LOCAL_MODEL_DIR = try_download_model(FALLBACK_MODEL)
    MODEL_NAME = FALLBACK_MODEL
else:
    MODEL_NAME = PRIMARY_MODEL

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

# -------------------------------
# 2. pipeline 載入 (Seq2SeqLM for T5)
# -------------------------------
tokenizer = AutoTokenizer.from_pretrained(LOCAL_MODEL_DIR)
model = AutoModelForSeq2SeqLM.from_pretrained(LOCAL_MODEL_DIR)

generator = pipeline(
    "text2text-generation",
    model=model,
    tokenizer=tokenizer,
    device=-1  # CPU
)

def call_local_inference(prompt, max_new_tokens=256):
    try:
        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. 建立/載入向量資料庫
# -------------------------------
EMBEDDINGS_MODEL_NAME = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
embeddings_model = HuggingFaceEmbeddings(model_name=EMBEDDINGS_MODEL_NAME)

DB_PATH = "./faiss_db"
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=5):
    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 系統")
    gr.Markdown("使用 FAISS + 中文 T5 模型,基於資料庫內容生成文章。")

    query_input = gr.Textbox(lines=2, placeholder="請輸入文章主題", label="文章主題")
    segments_input = gr.Slider(minimum=1, maximum=10, step=1, value=5, label="段落數")
    output_text = gr.Textbox(label="生成文章")
    output_file = gr.File(label="下載 DOCX")
    model_info = gr.Label(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()