Nerva5678 commited on
Commit
6778cfa
·
verified ·
1 Parent(s): 80a7908

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +285 -1
app.py CHANGED
@@ -31,4 +31,288 @@ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
31
  from langchain_community.vectorstores import FAISS
32
  from langchain_community.llms import HuggingFacePipeline
33
 
34
- # 其餘代碼保持不變...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  from langchain_community.vectorstores import FAISS
32
  from langchain_community.llms import HuggingFacePipeline
33
 
34
+ # 其餘代碼保持不變...
35
+
36
+ # 設定logging
37
+ logging.basicConfig(level=logging.INFO)
38
+ logger = logging.getLogger(__name__)
39
+
40
+ # 頁面配置
41
+ st.set_page_config(
42
+ page_title="Excel 問答 AI(ChatGLM 驅動)",
43
+ page_icon="🤖",
44
+ layout="wide"
45
+ )
46
+
47
+ # 應用標題與說明
48
+ st.title("🤖 Excel 問答 AI(ChatGLM 驅動)")
49
+ st.markdown("""
50
+ ### 使用說明
51
+ 1. 可直接提問一般知識,AI 將使用內建能力回答
52
+ 2. 上傳 Excel 檔案(包含「問題」和「答案」欄位)以添加專業知識
53
+ 3. 系統會優先使用您上傳的知識庫進行回答
54
+ """)
55
+
56
+ # 側邊欄設定
57
+ with st.sidebar:
58
+ st.header("參數設定")
59
+
60
+ model_option = st.selectbox(
61
+ "選擇模型",
62
+ ["THUDM/chatglm3-6b", "THUDM/chatglm2-6b", "THUDM/chatglm-6b"],
63
+ index=0
64
+ )
65
+
66
+ embedding_option = st.selectbox(
67
+ "選擇嵌入模型",
68
+ ["shibing624/text2vec-base-chinese", "GanymedeNil/text2vec-large-chinese"],
69
+ index=0
70
+ )
71
+
72
+ mode = st.radio(
73
+ "回答模式",
74
+ ["混合模式(優先使用上傳資料)", "僅使用上傳資料", "僅使用模型知識"]
75
+ )
76
+
77
+ max_tokens = st.slider("最大回應長度", 128, 2048, 512)
78
+ temperature = st.slider("溫度(創造性)", 0.0, 1.0, 0.7, 0.1)
79
+ top_k = st.slider("檢索相關文檔數", 1, 5, 3)
80
+
81
+ st.markdown("---")
82
+ st.markdown("### 關於")
83
+ st.markdown("此應用使用 ChatGLM 模型結合 LangChain 框架,將您的 Excel 數據轉化為智能問答系統。同時支持一般知識問答。")
84
+ st.markdown("📱 [GitHub 專案連結](https://github.com/yourusername/excel-qa-chatglm)")
85
+
86
+ # 全局變量
87
+ @st.cache_resource
88
+ def load_embeddings(model_name):
89
+ try:
90
+ logger.info(f"加載嵌入模型: {model_name}")
91
+ return HuggingFaceEmbeddings(model_name=model_name)
92
+ except Exception as e:
93
+ logger.error(f"嵌入模型加載失敗: {str(e)}")
94
+ st.error(f"嵌入模型加載失敗: {str(e)}")
95
+ return None
96
+
97
+ @st.cache_resource
98
+ def load_llm(_model_name, _max_tokens, _temperature):
99
+ try:
100
+ logger.info(f"加載語言模型: {_model_name}")
101
+
102
+ # 檢查是否有GPU可用
103
+ device = "cuda" if torch.cuda.is_available() else "cpu"
104
+ logger.info(f"使用設備: {device}")
105
+
106
+ # 加載模型和tokenizer
107
+ tokenizer = AutoTokenizer.from_pretrained(_model_name, trust_remote_code=True)
108
+ model = AutoModelForCausalLM.from_pretrained(
109
+ _model_name,
110
+ trust_remote_code=True,
111
+ device_map=device,
112
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32
113
+ )
114
+
115
+ # 創建pipeline
116
+ pipe = pipeline(
117
+ "text-generation",
118
+ model=model,
119
+ tokenizer=tokenizer,
120
+ max_new_tokens=_max_tokens,
121
+ temperature=_temperature,
122
+ top_p=0.9,
123
+ repetition_penalty=1.1
124
+ )
125
+
126
+ return HuggingFacePipeline(pipeline=pipe)
127
+ except Exception as e:
128
+ logger.error(f"語言模型加載失敗: {str(e)}")
129
+ st.error(f"語言模型加載失敗: {str(e)}")
130
+ return None
131
+
132
+ # 創建向量資料庫
133
+ def create_vectorstore(texts, embeddings):
134
+ try:
135
+ return FAISS.from_texts(texts, embedding=embeddings)
136
+ except Exception as e:
137
+ logger.error(f"向量資料庫創建失敗: {str(e)}")
138
+ st.error(f"向量資料庫創建失敗: {str(e)}")
139
+ return None
140
+
141
+ # 創建直接問答的LLM鏈
142
+ def create_general_qa_chain(llm):
143
+ prompt_template = """請回答以下問題:
144
+
145
+ 問題: {question}
146
+
147
+ 請提供詳細且有幫助的回答:"""
148
+
149
+ prompt = PromptTemplate(
150
+ template=prompt_template,
151
+ input_variables=["question"]
152
+ )
153
+
154
+ return LLMChain(llm=llm, prompt=prompt)
155
+
156
+ # 混合模式問答處理
157
+ def hybrid_qa(query, qa_chain, general_chain, confidence_threshold=0.7):
158
+ # 先嘗試使用知識庫回答
159
+ try:
160
+ kb_result = qa_chain({"query": query})
161
+ # 檢查向量存儲的相似度分數,判斷是否有足夠相關的內容
162
+ if hasattr(kb_result, 'source_documents') and len(kb_result["source_documents"]) > 0:
163
+ # 這裡假設我們能獲取到相似度分數,實際上可能需要根據您使用的向量存儲方法調整
164
+ relevance = True # 在實際應用中,這裡應根據相似度分數確定
165
+
166
+ if relevance:
167
+ return kb_result, "knowledge_base", kb_result["source_documents"]
168
+ except Exception as e:
169
+ logger.warning(f"知識庫查詢失敗: {str(e)}")
170
+
171
+ # 如果知識庫沒有足夠相關的答案,使用一般知識模式
172
+ try:
173
+ general_result = general_chain.run(question=query)
174
+ return {"result": general_result}, "general", []
175
+ except Exception as e:
176
+ logger.error(f"一般知識查詢失敗: {str(e)}")
177
+ return {"result": "很抱歉,無法處理您的問題,請稍後再試。"}, "error", []
178
+
179
+ # 主應用邏輯
180
+ # 加載語言模型(不管是否上傳文件都需要)
181
+ with st.spinner("正在加載AI模型..."):
182
+ llm = load_llm(model_option, max_tokens, temperature)
183
+ if llm is None:
184
+ st.error("語言模型加載失敗,請刷新頁面重試")
185
+ st.stop()
186
+
187
+ # 創建一般問答鏈
188
+ general_qa_chain = create_general_qa_chain(llm)
189
+
190
+ # 變數初始化
191
+ kb_qa_chain = None
192
+ has_knowledge_base = False
193
+ vectorstore = None
194
+
195
+ # 上傳Excel文件
196
+ uploaded_file = st.file_uploader("上傳你的問答 Excel(可選)", type=["xlsx"])
197
+
198
+ if uploaded_file:
199
+ # 讀取Excel文件
200
+ try:
201
+ df = pd.read_excel(uploaded_file)
202
+
203
+ # 檢查必要欄位
204
+ if not {'問題', '答案'}.issubset(df.columns):
205
+ st.error("Excel 檔案需包含 '問題' 和 '答案' 欄位")
206
+ else:
207
+ # 顯示資料預覽
208
+ with st.expander("Excel 資料預覽"):
209
+ st.dataframe(df.head())
210
+
211
+ st.info(f"成功讀取 {len(df)} 筆問答對")
212
+
213
+ # 建立文本列表
214
+ texts = [f"問題:{q}\n答案:{a}" for q, a in zip(df['問題'], df['答案'])]
215
+
216
+ # 進度條
217
+ progress_text = "正在處理中..."
218
+ my_bar = st.progress(0, text=progress_text)
219
+
220
+ # 加載嵌入模型
221
+ my_bar.progress(25, text="正在加載嵌入模型...")
222
+ embeddings = load_embeddings(embedding_option)
223
+ if embeddings is None:
224
+ st.stop()
225
+
226
+ # 建立向量資料庫
227
+ my_bar.progress(50, text="正在建立向量資料庫...")
228
+ vectorstore = create_vectorstore(texts, embeddings)
229
+ if vectorstore is None:
230
+ st.stop()
231
+
232
+ # 創建問答鏈
233
+ my_bar.progress(75, text="正在建立知識庫問答系統...")
234
+ kb_qa_chain = RetrievalQA.from_chain_type(
235
+ llm=llm,
236
+ retriever=vectorstore.as_retriever(search_kwargs={"k": top_k}),
237
+ chain_type="stuff",
238
+ return_source_documents=True
239
+ )
240
+
241
+ has_knowledge_base = True
242
+
243
+ my_bar.progress(100, text="準備完成!")
244
+ time.sleep(1)
245
+ my_bar.empty()
246
+
247
+ st.success("知識庫已準備就緒,請輸入您的問題")
248
+
249
+ except Exception as e:
250
+ logger.error(f"Excel 檔案處理失敗: {str(e)}")
251
+ st.error(f"Excel 檔案處理失敗: {str(e)}")
252
+
253
+ # 查詢部分
254
+ st.markdown("## 開始對話")
255
+ query = st.text_input("請輸入你的問題:")
256
+
257
+ if query:
258
+ with st.spinner("AI 思考中..."):
259
+ try:
260
+ start_time = time.time()
261
+
262
+ # 根據模式選擇問答方式
263
+ if mode == "僅使用上傳資料":
264
+ if has_knowledge_base:
265
+ result = kb_qa_chain({"query": query})
266
+ source = "knowledge_base"
267
+ source_docs = result["source_documents"]
268
+ else:
269
+ st.warning("您選擇了僅使用上傳資料模式,但尚未上傳Excel檔案。請上傳檔案或變更模式。")
270
+ st.stop()
271
+
272
+ elif mode == "僅使用模型知識":
273
+ result = {"result": general_qa_chain.run(question=query)}
274
+ source = "general"
275
+ source_docs = []
276
+
277
+ else: # 混合模式
278
+ if has_knowledge_base:
279
+ result, source, source_docs = hybrid_qa(query, kb_qa_chain, general_qa_chain)
280
+ else:
281
+ result = {"result": general_qa_chain.run(question=query)}
282
+ source = "general"
283
+ source_docs = []
284
+
285
+ end_time = time.time()
286
+
287
+ # 顯示回答
288
+ st.markdown("### AI 回答:")
289
+ st.markdown(result["result"])
290
+
291
+ # 根據來源顯示不同信息
292
+ if source == "knowledge_base":
293
+ st.success("✅ 回答來自您的知識庫")
294
+ # 顯示參考資料
295
+ with st.expander("參考資料"):
296
+ for i, doc in enumerate(source_docs):
297
+ st.markdown(f"**參考 {i+1}**")
298
+ st.markdown(doc.page_content)
299
+ st.markdown("---")
300
+ elif source == "general":
301
+ if has_knowledge_base:
302
+ st.info("ℹ️ 回答來自模型的一般知識(知識庫中未找到相關內容���")
303
+ else:
304
+ st.info("ℹ️ 回答來自模型的一般知識")
305
+
306
+ st.text(f"回答生成時間: {(end_time - start_time):.2f} 秒")
307
+
308
+ except Exception as e:
309
+ logger.error(f"查詢處理失敗: {str(e)}")
310
+ st.error(f"查詢處理失敗,請重試: {str(e)}")
311
+
312
+ # 添加會話歷史功能
313
+ if "chat_history" not in st.session_state:
314
+ st.session_state.chat_history = []
315
+
316
+ # 底部資訊
317
+ st.markdown("---")
318
+ st.markdown("Made with ❤️ | 若需支援,請聯繫 [[email protected]](mailto:[email protected])")