CHUNYU0505 commited on
Commit
d051231
·
verified ·
1 Parent(s): 6f0de2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -11
app.py CHANGED
@@ -1,3 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
1
  # -------------------------------
2
  # 0. 載入向量資料庫
3
  # -------------------------------
@@ -6,7 +17,7 @@ embeddings_model = HuggingFaceEmbeddings(model_name=EMBEDDINGS_MODEL_NAME)
6
 
7
  DB_PATH = "./faiss_db"
8
  if os.path.exists(DB_PATH):
9
- print("載入現有向量資料庫...")
10
  db = FAISS.load_local(DB_PATH, embeddings_model, allow_dangerous_deserialization=True)
11
  else:
12
  raise ValueError("❌ 沒找到 faiss_db,請先建立向量資料庫")
@@ -14,17 +25,81 @@ else:
14
  retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": 5})
15
 
16
  # -------------------------------
17
- # 文章生成(RAG + 檢索片段 + 進度提示 + 即時寫入DOCX
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  # -------------------------------
19
  def generate_article_progress(query, segments=5):
20
  docx_file = "/tmp/generated_article.docx"
21
  doc = DocxDocument()
22
  doc.add_heading(query, level=1)
23
- doc.save(docx_file) # 先建立空的 docx,避免後面保存出錯
24
 
25
  all_text = []
26
 
27
- # 🔍 使用 RAG 從 FAISS 檢索相關文獻
28
  retrieved_docs = retriever.get_relevant_documents(query)
29
  context_texts = [d.page_content for d in retrieved_docs]
30
  context = "\n".join([f"{i+1}. {txt}" for i, txt in enumerate(context_texts[:3])])
@@ -39,9 +114,9 @@ def generate_article_progress(query, segments=5):
39
  paragraph = call_local_inference(prompt)
40
  all_text.append(paragraph)
41
 
42
- # ✅ 每段生成後立即寫入 DOCX
43
- doc = DocxDocument(docx_file) # 重新打開現有的檔案
44
- doc.add_paragraph(paragraph)
45
  doc.save(docx_file)
46
 
47
  yield "\n\n".join(all_text), None, f"本次使用模型:{MODEL_NAME}", context, progress_text
@@ -49,25 +124,26 @@ def generate_article_progress(query, segments=5):
49
  final_progress = f"✅ 已完成全部 {segments} 段生成!"
50
  yield "\n\n".join(all_text), docx_file, f"本次使用模型:{MODEL_NAME}", context, final_progress
51
 
52
-
53
  # -------------------------------
54
- # Gradio 介面
55
  # -------------------------------
56
  with gr.Blocks() as demo:
57
  gr.Markdown("# 📺 電視弘法視頻生成文章RAG系統")
58
- gr.Markdown("使用 GPT2-Chinese + FAISS RAG,生成文章。")
59
 
60
  query_input = gr.Textbox(lines=2, placeholder="請輸入文章主題", label="文章主題")
61
  segments_input = gr.Slider(minimum=1, maximum=10, step=1, value=5, label="段落數")
62
  output_text = gr.Textbox(label="生成文章")
63
  output_file = gr.File(label="下載 DOCX")
64
  model_used_text = gr.Textbox(label="實際使用模型", interactive=False)
 
 
65
 
66
  btn = gr.Button("生成文章")
67
  btn.click(
68
  generate_article_progress,
69
  inputs=[query_input, segments_input],
70
- outputs=[output_text, output_file, model_used_text]
71
  )
72
 
73
  if __name__ == "__main__":
 
1
+ # app.py
2
+ import os, torch
3
+ from langchain.docstore.document import Document
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain_community.vectorstores import FAISS
6
+ from langchain_huggingface import HuggingFaceEmbeddings
7
+ from docx import Document as DocxDocument
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
9
+ from huggingface_hub import login, snapshot_download
10
+ import gradio as gr
11
+
12
  # -------------------------------
13
  # 0. 載入向量資料庫
14
  # -------------------------------
 
17
 
18
  DB_PATH = "./faiss_db"
19
  if os.path.exists(DB_PATH):
20
+ print("載入現有向量資料庫...")
21
  db = FAISS.load_local(DB_PATH, embeddings_model, allow_dangerous_deserialization=True)
22
  else:
23
  raise ValueError("❌ 沒找到 faiss_db,請先建立向量資料庫")
 
25
  retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": 5})
26
 
27
  # -------------------------------
28
+ # 1. 模型設定(中文 GPT2 + fallback
29
+ # -------------------------------
30
+ PRIMARY_MODEL = "uer/gpt2-chinese-cluecorpusmedium"
31
+ FALLBACK_MODEL = "uer/gpt2-chinese-cluecorpussmall"
32
+
33
+ HF_TOKEN = os.environ.get("HUGGINGFACEHUB_API_TOKEN")
34
+ if HF_TOKEN:
35
+ login(token=HF_TOKEN)
36
+ print("✅ 已使用 HUGGINGFACEHUB_API_TOKEN 登入 Hugging Face")
37
+
38
+ def try_download_model(repo_id):
39
+ local_dir = f"./models/{repo_id.split('/')[-1]}"
40
+ if not os.path.exists(local_dir):
41
+ print(f"⬇️ 嘗試下載模型 {repo_id} ...")
42
+ try:
43
+ snapshot_download(repo_id=repo_id, token=HF_TOKEN, local_dir=local_dir)
44
+ except Exception as e:
45
+ print(f"⚠️ 模型 {repo_id} 無法下載: {e}")
46
+ return None
47
+ return local_dir
48
+
49
+ LOCAL_MODEL_DIR = try_download_model(PRIMARY_MODEL)
50
+ if LOCAL_MODEL_DIR is None:
51
+ print("⚠️ 切換到 fallback 模型:小型 GPT2-Chinese")
52
+ LOCAL_MODEL_DIR = try_download_model(FALLBACK_MODEL)
53
+ MODEL_NAME = FALLBACK_MODEL
54
+ else:
55
+ MODEL_NAME = PRIMARY_MODEL
56
+
57
+ print(f"👉 最終使用模型:{MODEL_NAME}")
58
+
59
+ # -------------------------------
60
+ # 2. pipeline 載入
61
+ # -------------------------------
62
+ tokenizer = AutoTokenizer.from_pretrained(LOCAL_MODEL_DIR)
63
+ model = AutoModelForCausalLM.from_pretrained(LOCAL_MODEL_DIR)
64
+
65
+ # 修正 pad_token 缺失問題
66
+ if tokenizer.pad_token is None:
67
+ tokenizer.pad_token = tokenizer.eos_token
68
+
69
+ generator = pipeline(
70
+ "text-generation",
71
+ model=model,
72
+ tokenizer=tokenizer,
73
+ device=-1 # CPU
74
+ )
75
+
76
+ def call_local_inference(prompt, max_new_tokens=256):
77
+ try:
78
+ if "中文" not in prompt:
79
+ prompt += "\n(請用中文回答)"
80
+ outputs = generator(
81
+ prompt,
82
+ max_new_tokens=max_new_tokens,
83
+ do_sample=True,
84
+ temperature=0.7,
85
+ pad_token_id=tokenizer.pad_token_id
86
+ )
87
+ return outputs[0]["generated_text"]
88
+ except Exception as e:
89
+ return f"(生成失敗:{e})"
90
+
91
+ # -------------------------------
92
+ # 3. 文章生成(RAG + 即時寫入DOCX + 檢索片段 + 進度提示)
93
  # -------------------------------
94
  def generate_article_progress(query, segments=5):
95
  docx_file = "/tmp/generated_article.docx"
96
  doc = DocxDocument()
97
  doc.add_heading(query, level=1)
98
+ doc.save(docx_file) # 先建立空的檔案
99
 
100
  all_text = []
101
 
102
+ # 🔍 RAG 檢索佛經段落
103
  retrieved_docs = retriever.get_relevant_documents(query)
104
  context_texts = [d.page_content for d in retrieved_docs]
105
  context = "\n".join([f"{i+1}. {txt}" for i, txt in enumerate(context_texts[:3])])
 
114
  paragraph = call_local_inference(prompt)
115
  all_text.append(paragraph)
116
 
117
+ # ✅ 每段生成後即時寫入 DOCX
118
+ doc = DocxDocument(docx_file)
119
+ doc.add_paragraph(f"第{i+1}段:\n{paragraph}")
120
  doc.save(docx_file)
121
 
122
  yield "\n\n".join(all_text), None, f"本次使用模型:{MODEL_NAME}", context, progress_text
 
124
  final_progress = f"✅ 已完成全部 {segments} 段生成!"
125
  yield "\n\n".join(all_text), docx_file, f"本次使用模型:{MODEL_NAME}", context, final_progress
126
 
 
127
  # -------------------------------
128
+ # 4. Gradio 介面
129
  # -------------------------------
130
  with gr.Blocks() as demo:
131
  gr.Markdown("# 📺 電視弘法視頻生成文章RAG系統")
132
+ gr.Markdown("使用 GPT2-Chinese + FAISS RAG,生成佛教主題文章。")
133
 
134
  query_input = gr.Textbox(lines=2, placeholder="請輸入文章主題", label="文章主題")
135
  segments_input = gr.Slider(minimum=1, maximum=10, step=1, value=5, label="段落數")
136
  output_text = gr.Textbox(label="生成文章")
137
  output_file = gr.File(label="下載 DOCX")
138
  model_used_text = gr.Textbox(label="實際使用模型", interactive=False)
139
+ context_text = gr.Textbox(label="檢索到的佛經片段", interactive=False, lines=6)
140
+ progress_text = gr.Textbox(label="生成進度", interactive=False)
141
 
142
  btn = gr.Button("生成文章")
143
  btn.click(
144
  generate_article_progress,
145
  inputs=[query_input, segments_input],
146
+ outputs=[output_text, output_file, model_used_text, context_text, progress_text]
147
  )
148
 
149
  if __name__ == "__main__":