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

Upload 2 files

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