aihuashanying commited on
Commit
81c15be
·
verified ·
1 Parent(s): a9a7c0b

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +364 -0
app.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ from langchain_community.document_loaders import TextLoader, DirectoryLoader
5
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
6
+ from langchain_community.vectorstores import FAISS
7
+ from langchain_openai import ChatOpenAI
8
+ from langchain.prompts import PromptTemplate
9
+ import numpy as np
10
+ import faiss
11
+ from collections import deque
12
+ from langchain_core.embeddings import Embeddings
13
+ import threading
14
+ import queue
15
+ from langchain_core.messages import HumanMessage, AIMessage
16
+ from sentence_transformers import SentenceTransformer
17
+ import pickle
18
+ import torch
19
+ import time
20
+ from tqdm import tqdm
21
+ import logging
22
+
23
+ # 设置日志
24
+ logging.basicConfig(level=logging.INFO)
25
+ logger = logging.getLogger(__name__)
26
+
27
+ # 获取环境变量
28
+ os.environ["OPENROUTER_API_KEY"] = os.getenv("OPENROUTER_API_KEY", "")
29
+ if not os.environ["OPENROUTER_API_KEY"]:
30
+ raise ValueError("OPENROUTER_API_KEY 未设置")
31
+ SILICONFLOW_API_KEY = os.getenv("SILICONFLOW_API_KEY")
32
+ if not SILICONFLOW_API_KEY:
33
+ raise ValueError("SILICONFLOW_API_KEY 未设置")
34
+ BYTEZ_API_KEY = os.getenv("BYTEZ_API_KEY")
35
+ if not BYTEZ_API_KEY:
36
+ raise ValueError("BYTEZ_API_KEY no set")
37
+
38
+ # SiliconFlow API 配置
39
+ BYTEZ_API_URL = "https://api.bytez.com/models/v2/BAAI/bge-reranker-v2-m3"
40
+ SILICONFLOW_API_URL = "https://api.siliconflow.cn/v1/rerank"
41
+
42
+ # 自定义嵌入类,优化查询缓存
43
+ class SentenceTransformerEmbeddings(Embeddings):
44
+ def __init__(self, model_name="BAAI/bge-m3"):
45
+ device = "cuda" if torch.cuda.is_available() else "cpu"
46
+ self.model = SentenceTransformer(model_name, device=device)
47
+ self.batch_size = 32 # 减小批次大小以适应低内存
48
+ self.query_cache = {}
49
+ self.cache_lock = threading.Lock()
50
+
51
+ def embed_documents(self, texts):
52
+ embeddings_list = []
53
+ batch_size = 1000 # 减小批次以降低内存压力
54
+ total_chunks = len(texts)
55
+ logger.info(f"生成嵌入,文档数: {total_chunks}")
56
+ with torch.no_grad():
57
+ for i in tqdm(range(0, total_chunks, batch_size), desc="生成嵌入"):
58
+ batch_texts = [text.page_content for text in texts[i:i + batch_size]]
59
+ batch_emb = self.model.encode(
60
+ batch_texts,
61
+ normalize_embeddings=True,
62
+ batch_size=self.batch_size
63
+ )
64
+ embeddings_list.append(batch_emb)
65
+ embeddings_array = np.vstack(embeddings_list)
66
+ np.save("embeddings.npy", embeddings_array)
67
+ return embeddings_array
68
+
69
+ def embed_query(self, text):
70
+ with self.cache_lock:
71
+ if text in self.query_cache:
72
+ return self.query_cache[text]
73
+ with torch.no_grad():
74
+ emb = self.model.encode([text], normalize_embeddings=True, batch_size=1)[0]
75
+ with self.cache_lock:
76
+ self.query_cache[text] = emb
77
+ if len(self.query_cache) > 1000: # 限制缓存大小
78
+ self.query_cache.pop(next(iter(self.query_cache)))
79
+ return emb
80
+
81
+ # 重排序函数
82
+ def rerank_documents(query, documents, top_n=15):
83
+ try:
84
+ doc_texts_with_meta = []
85
+ for doc in documents[:50]:
86
+ if isinstance(doc, tuple):
87
+ actual_doc = doc[0]
88
+ else:
89
+ actual_doc = doc
90
+
91
+ if hasattr(actual_doc, 'page_content'):
92
+ text = actual_doc.page_content[:2048]
93
+ book_meta = actual_doc.metadata.get("book", "unknow source")
94
+ doc_texts_with_meta.append((text, book_meta))
95
+ else:
96
+ logger.warning(f"skip the invalid texts: {type(doc)}")
97
+
98
+ headers = {"Authorization": f"Bearer {BYTEZ_API_KEY}", "Content-Type": "application/json"}
99
+ data = {"query": query, "text": [text for text, _ in doc_texts_with_meta], "top_n": top_n}
100
+ response = requests.post(BYTEZ_API_URL, headers=headers, json=data)
101
+ response.raise_for_status()
102
+ result = response.json()
103
+
104
+ '''
105
+ import json
106
+ print("---api result---")
107
+ print(json.dumps(result, indent=2, ensure_ascii=False))
108
+ print("-----------------------")
109
+ '''
110
+
111
+ reranked_docs = []
112
+ for res in result["output"]:
113
+ score = res["score"]
114
+ pass
115
+ reranked_results = []
116
+ for i, res in enumerate(result["output"]):
117
+ score = res["score"]
118
+ if i < len(documents):
119
+ if isinstance(documents[i], tuple):
120
+ original_doc = documents[i][0]
121
+ else:
122
+ original_doc = documents[i]
123
+ reranked_results.append((original_doc, score))
124
+ return sorted(reranked_results, key=lambda x: x[1], reverse=True)[:top_n]
125
+ except Exception as e:
126
+ logger.error(f"重���序失败: {str(e)}")
127
+ raise
128
+
129
+ # 构建 HNSW 索引
130
+ def build_hnsw_index(knowledge_base_path, index_path):
131
+ loader = DirectoryLoader(knowledge_base_path, glob="*.txt", loader_cls=lambda path: TextLoader(path, encoding="utf-8"))
132
+ documents = loader.load()
133
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
134
+ texts = text_splitter.split_documents(documents)
135
+ for i, doc in enumerate(texts):
136
+ doc.metadata["book"] = os.path.basename(doc.metadata.get("source", "未知来源")).replace(".txt", "")
137
+ embeddings_array = embeddings.embed_documents(texts)
138
+ dimension = embeddings_array.shape[1]
139
+ index = faiss.IndexHNSWFlat(dimension, 16)
140
+ index.hnsw.efConstruction = 100
141
+ index.add(embeddings_array)
142
+ vector_store = FAISS.from_embeddings([(doc.page_content, embeddings_array[i]) for i, doc in enumerate(texts)], embeddings)
143
+ vector_store.index = index
144
+ vector_store.save_local(index_path)
145
+ with open("chunks.pkl", "wb") as f:
146
+ pickle.dump(texts, f)
147
+ return vector_store, texts
148
+
149
+ # 初始化嵌入模型和索引
150
+ embeddings = SentenceTransformerEmbeddings()
151
+ index_path = "faiss_index_hnsw_new"
152
+ knowledge_base_path = "knowledge_base"
153
+
154
+ if not os.path.exists(index_path):
155
+ vector_store, all_documents = build_hnsw_index(knowledge_base_path, index_path)
156
+ else:
157
+ vector_store = FAISS.load_local(index_path, embeddings=embeddings, allow_dangerous_deserialization=True)
158
+ vector_store.index.hnsw.efSearch = 200 # 降低 efSearch 以提升速度
159
+ with open("chunks.pkl", "rb") as f:
160
+ all_documents = pickle.load(f)
161
+
162
+ # 初始化 LLM
163
+ llm = ChatOpenAI(
164
+ model="tngtech/deepseek-r1t2-chimera:free",
165
+ api_key=os.environ["OPENROUTER_API_KEY"],
166
+ base_url="https://openrouter.ai/api/v1",
167
+ timeout=100,
168
+ temperature=0.3,
169
+ max_tokens=130000,
170
+ streaming=True
171
+ )
172
+
173
+ # 提示词模板
174
+ prompt_template = PromptTemplate(
175
+ input_variables=["context", "question", "chat_history"],
176
+ template="""
177
+ 你是一个研究李敖的专家,根据用户提出的问题{question}、最近7轮对话历史{chat_history}以及从李敖相关书籍和评论中检索的至少10篇文本内容{context}回答问题。
178
+ 在回答时,请注意以下几点:
179
+ - 结合李敖的写作风格和思想,筛选出与问题和对话历史最相关的检索内容,避免无关信息。
180
+ - 必须在回答中引用至少10篇不同的文本内容,引用格式为[引用: 文本序号],例如[引用: 1][引用: 2],并确保每篇文本在回答中都有明确使用。
181
+ - 在回答的末尾,必须以“引用文献”标题列出所有引用的文本序号及其内容摘要(每篇不超过50字)以及具体的书目信息(例如书名和章节),格式为:
182
+ - 引用文献:
183
+ 1. [文本 1] 摘要... 出自:书名,第X页/章节。
184
+ 2. [文本 2] 摘要... 出自:书名,第X页/章节。
185
+ (依此类推,至少10篇)
186
+ - 如果问题涉及李敖对某人或某事的评价,优先引用李敖的直接言论或文字,并说明出处。
187
+ - 回答应结构化、分段落,确保逻辑清晰,语言生动,类似李敖的犀利风格。
188
+ - 如果检索内容和历史不足以直接回答问题,可根据李敖的性格和观点推测其可能的看法,但需说明这是推测。
189
+ - 只能基于提供的知识库内容{context}和对话历史{chat_history}回答,不得引入外部信息。
190
+ - 对于列举类问题,控制在10个要点以内,并优先提供最相关项。
191
+ - 如果回答较长,结构化分段总结,分点作答控制在8个点以内。
192
+ - 对于客观类的问答,如果问题的答案非常简短,可以适当补充一到两句相关信息,以丰富内容。
193
+ - 你需要根据用户要求和回答内容选择合适、美观的回答格式,确保可读性强。
194
+ - 你的回答应该综合多个相关知识库内容来回答,不能重复引用一个知识库内容。
195
+ - 除非用户要求,否则你回答的语言需要和用户提问的语言保持一致。
196
+ """
197
+ )
198
+
199
+ # 对话历史管理
200
+ class ConversationHistory:
201
+ def __init__(self, max_length=5): # 减少历史轮数
202
+ self.history = deque(maxlen=max_length)
203
+
204
+ def add_turn(self, question, answer):
205
+ self.history.append((question, answer))
206
+
207
+ def get_history(self):
208
+ return [(q, a) for q, a in self.history]
209
+
210
+ # 用户会话状态
211
+ class UserSession:
212
+ def __init__(self):
213
+ self.conversation = ConversationHistory()
214
+ self.output_queue = queue.Queue()
215
+ self.stop_flag = threading.Event()
216
+
217
+ # 生成回答
218
+ def generate_answer_thread(question, session):
219
+ stop_flag = session.stop_flag
220
+ output_queue = session.output_queue
221
+ conversation = session.conversation
222
+
223
+ stop_flag.clear()
224
+ try:
225
+ # 打印用户���题到控制台
226
+ logger.info(f"用户问题: {question}")
227
+
228
+ history_list = conversation.get_history()
229
+ history_text = "\n".join([f"问: {q}\n答: {a}" for q, a in history_list[-3:]]) # 只用最后3轮
230
+ query_with_context = f"{history_text}\n问题: {question}" if history_text else question
231
+
232
+ # 异步生成查询嵌入
233
+ embed_queue = queue.Queue()
234
+ def embed_task():
235
+ start = time.time()
236
+ emb = embeddings.embed_query(query_with_context)
237
+ embed_queue.put((emb, time.time() - start))
238
+ embed_thread = threading.Thread(target=embed_task)
239
+ embed_thread.start()
240
+ embed_thread.join()
241
+ query_embedding, embed_time = embed_queue.get()
242
+
243
+ if stop_flag.is_set():
244
+ output_queue.put("生成已停止")
245
+ return
246
+
247
+ # 初始检索
248
+ start = time.time()
249
+ docs_with_scores = vector_store.similarity_search_with_score_by_vector(query_embedding, k=50)
250
+ search_time = time.time() - start
251
+
252
+ if stop_flag.is_set():
253
+ output_queue.put("生成已停止")
254
+ return
255
+
256
+ # 重排序
257
+ initial_docs = [doc for doc, _ in docs_with_scores]
258
+ start = time.time()
259
+ reranked_docs_with_scores = rerank_documents(query_with_context, initial_docs)
260
+ rerank_time = time.time() - start
261
+ final_docs = [doc for doc, _ in reranked_docs_with_scores][:10]
262
+
263
+ # 打印重排序结果到控制台
264
+ logger.info("重排序结果(最终保留的片段及其得分):")
265
+ for i, (doc, score) in enumerate(reranked_docs_with_scores[:10], 1):
266
+ logger.info(f"片段 {i}:")
267
+ logger.info(f" 内容: {doc.page_content[:100]}...")
268
+ logger.info(f" 来源: {doc.metadata.get('book', '未知来源')}")
269
+ logger.info(f" 得分: {score:.4f}")
270
+
271
+ context = "\n".join([f"[文本 {i+1}] {doc.page_content} (出处: {doc.metadata.get('book')})" for i, doc in enumerate(final_docs)])
272
+ prompt = prompt_template.format(context=context, question=question, chat_history=history_text)
273
+
274
+ # 将时间信息加入回答开头
275
+ timing_info = (
276
+ f"处理时间统计:\n"
277
+ f"- 嵌入时间: {embed_time:.2f} 秒\n"
278
+ f"- 检索时间: {search_time:.2f} 秒\n"
279
+ f"- 重排序时间: {rerank_time:.2f} 秒\n\n"
280
+ )
281
+
282
+ answer = timing_info
283
+ output_queue.put(answer) # 先显示时间信息
284
+
285
+ # LLM 生成回答
286
+ start = time.time()
287
+ for chunk in llm.stream([HumanMessage(content=prompt)]):
288
+ if stop_flag.is_set():
289
+ output_queue.put(answer + "\n(生成已停止)")
290
+ return
291
+ answer += chunk.content
292
+ output_queue.put(answer)
293
+ llm_time = time.time() - start
294
+ answer += f"\n\n生成耗时: {llm_time:.2f} 秒"
295
+ output_queue.put(answer)
296
+
297
+ conversation.add_turn(question, answer)
298
+ output_queue.put(answer)
299
+
300
+ except Exception as e:
301
+ output_queue.put(f"Error: {str(e)}")
302
+
303
+ # Gradio 接口
304
+ def answer_question(question, session_state):
305
+ if session_state is None:
306
+ session_state = UserSession()
307
+
308
+ thread = threading.Thread(target=generate_answer_thread, args=(question, session_state))
309
+ thread.start()
310
+
311
+ while thread.is_alive() or not session_state.output_queue.empty():
312
+ try:
313
+ output = session_state.output_queue.get(timeout=0.1)
314
+ yield output, session_state
315
+ except queue.Empty:
316
+ continue
317
+
318
+ def stop_generation(session_state):
319
+ if session_state:
320
+ session_state.stop_flag.set()
321
+ return "生成已停止"
322
+
323
+ def clear_conversation():
324
+ return "对话已清空", UserSession()
325
+
326
+ # 自动提问功能:每天触发一次“介绍一下李敖”
327
+ def auto_ask_question():
328
+ auto_session = UserSession()
329
+ last_run_time = 0
330
+ interval = 24 * 60 * 60 # 24小时(单位:秒)
331
+
332
+ while True:
333
+ current_time = time.time()
334
+ if current_time - last_run_time >= interval:
335
+ logger.info("自动触发问题:介绍一下李敖")
336
+ thread = threading.Thread(target=generate_answer_thread, args=("介绍一下李敖", auto_session))
337
+ thread.start()
338
+ thread.join() # 等待回答生成完成
339
+ last_run_time = current_time
340
+ time.sleep(60) # 每分钟检查一次,避免占用过多资源
341
+
342
+ # Gradio 界面
343
+ with gr.Blocks(title="AI李敖助手") as interface:
344
+ gr.Markdown("## AI李敖助手")
345
+ gr.Markdown("### 作者:爱华山樱")
346
+ gr.Markdown("基于李敖163本相关书籍构建的知识库,支持上下文关联,记住最近5轮对话,输入问题以获取李敖风格的回答。")
347
+ gr.Markdown("提问之后红框存在期间表示正在生成回答��如果红框消失之后答案没出来,说明生成有问题(偶尔会这样),重来一次即可。")
348
+ session_state = gr.State(value=None)
349
+ question_input = gr.Textbox(label="问题")
350
+ submit_button = gr.Button("提交")
351
+ clear_button = gr.Button("新建对话")
352
+ stop_button = gr.Button("停止生成")
353
+ output_text = gr.Textbox(label="回答", interactive=False)
354
+
355
+ submit_button.click(fn=answer_question, inputs=[question_input, session_state], outputs=[output_text, session_state])
356
+ clear_button.click(fn=clear_conversation, inputs=None, outputs=[output_text, session_state])
357
+ stop_button.click(fn=stop_generation, inputs=[session_state], outputs=output_text)
358
+
359
+ if __name__ == "__main__":
360
+ # 启动自动提问线程
361
+ auto_thread = threading.Thread(target=auto_ask_question, daemon=True)
362
+ auto_thread.start()
363
+ # 启动 Gradio 界面
364
+ interface.launch(share=True)