Spaces:
Paused
Paused
lanny xu
commited on
Commit
·
9e3fc83
1
Parent(s):
8f47b0a
optimize query speed
Browse files- document_processor.py +142 -79
document_processor.py
CHANGED
|
@@ -252,43 +252,27 @@ class DocumentProcessor:
|
|
| 252 |
print(f"文档分割完成,共 {len(doc_splits)} 个文档块")
|
| 253 |
return doc_splits
|
| 254 |
|
| 255 |
-
def
|
| 256 |
-
"""
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
"""
|
| 262 |
-
print("正在创建向量数据库...")
|
| 263 |
-
|
| 264 |
-
# 如果没有指定持久化目录,使用默认相对路径
|
| 265 |
-
if persist_directory is None:
|
| 266 |
-
import os
|
| 267 |
-
current_dir = os.path.dirname(os.path.abspath(__file__))
|
| 268 |
-
persist_directory = os.path.join(current_dir, 'milvus_data')
|
| 269 |
-
os.makedirs(persist_directory, exist_ok=True)
|
| 270 |
-
# print(f"💾 使用默认持久化目录: {persist_directory}") # Milvus 不需要这个
|
| 271 |
|
| 272 |
# 强制使用 Milvus
|
| 273 |
try:
|
| 274 |
# 准备连接参数
|
| 275 |
connection_args = {}
|
| 276 |
|
| 277 |
-
# 优先使用 URI
|
| 278 |
-
# 只要 MILVUS_URI 被设置(config中默认是 ./milvus_rag.db),且不是空字符串
|
| 279 |
if MILVUS_URI and len(MILVUS_URI.strip()) > 0:
|
| 280 |
-
# 判断是本地文件还是云服务
|
| 281 |
is_local_file = not (MILVUS_URI.startswith("http://") or MILVUS_URI.startswith("https://"))
|
| 282 |
mode_name = "Lite (Local File)" if is_local_file else "Cloud (HTTP)"
|
| 283 |
-
|
| 284 |
print(f"🔄 正在连接 Milvus {mode_name} ({MILVUS_URI})...")
|
| 285 |
connection_args["uri"] = MILVUS_URI
|
| 286 |
-
|
| 287 |
-
# 如果是云服务,通常需要 token (使用 password 字段作为 token)
|
| 288 |
if not is_local_file and MILVUS_PASSWORD:
|
| 289 |
connection_args["token"] = MILVUS_PASSWORD
|
| 290 |
else:
|
| 291 |
-
# 传统的 Host/Port 连接
|
| 292 |
print(f"🔄 正在连接 Milvus Server ({MILVUS_HOST}:{MILVUS_PORT})...")
|
| 293 |
connection_args = {
|
| 294 |
"host": MILVUS_HOST,
|
|
@@ -297,23 +281,9 @@ class DocumentProcessor:
|
|
| 297 |
"password": MILVUS_PASSWORD
|
| 298 |
}
|
| 299 |
|
| 300 |
-
#
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
# 实际应用中,你应该在 split_documents 阶段就给文档打好标签
|
| 304 |
-
for doc in doc_splits:
|
| 305 |
-
if 'source_type' not in doc.metadata:
|
| 306 |
-
# 简单逻辑:根据内容判断是文本还是图像描述(如果是多模态)
|
| 307 |
-
# 或者根据文件名后缀判断
|
| 308 |
-
source = doc.metadata.get('source', '')
|
| 309 |
-
if any(fmt in source.lower() for fmt in SUPPORTED_IMAGE_FORMATS):
|
| 310 |
-
doc.metadata['data_type'] = 'image'
|
| 311 |
-
else:
|
| 312 |
-
doc.metadata['data_type'] = 'text'
|
| 313 |
-
|
| 314 |
-
self.vectorstore = Milvus.from_documents(
|
| 315 |
-
documents=doc_splits,
|
| 316 |
-
embedding=self.embeddings,
|
| 317 |
collection_name=COLLECTION_NAME,
|
| 318 |
connection_args=connection_args,
|
| 319 |
index_params={
|
|
@@ -325,51 +295,93 @@ class DocumentProcessor:
|
|
| 325 |
"metric_type": "L2",
|
| 326 |
"params": MILVUS_SEARCH_PARAMS
|
| 327 |
},
|
| 328 |
-
drop_old=
|
|
|
|
| 329 |
)
|
| 330 |
-
print("✅ Milvus
|
| 331 |
except ImportError:
|
| 332 |
print("❌ 未安装 pymilvus,请运行: pip install pymilvus")
|
| 333 |
raise
|
| 334 |
except Exception as e:
|
| 335 |
print(f"❌ Milvus 连接失败: {e}")
|
| 336 |
-
raise
|
| 337 |
-
|
| 338 |
-
#
|
| 339 |
-
# 默认情况下不添加严格过滤,由上层逻辑决定
|
| 340 |
-
# 但如果只启用纯文本检索,可以默认只检索文本
|
| 341 |
retriever_kwargs = {}
|
| 342 |
# if ENABLE_MULTIMODAL:
|
| 343 |
-
# 针对文本检索,过滤出 data_type='text' 的数据
|
| 344 |
-
# 注意:这里注释掉是为了支持通过文本检索图像的场景
|
| 345 |
# retriever_kwargs["expr"] = "data_type == 'text'"
|
| 346 |
-
|
| 347 |
self.retriever = self.vectorstore.as_retriever(search_kwargs=retriever_kwargs)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
doc_splits,
|
| 356 |
-
k=KEYWORD_SEARCH_K,
|
| 357 |
-
k1=BM25_K1,
|
| 358 |
-
b=BM25_B
|
| 359 |
-
)
|
| 360 |
-
|
| 361 |
-
# 创建集成检索器,结合向量检索和BM25检索
|
| 362 |
-
self.ensemble_retriever = CustomEnsembleRetriever(
|
| 363 |
-
retrievers=[self.retriever, self.bm25_retriever],
|
| 364 |
-
weights=[HYBRID_SEARCH_WEIGHTS["vector"], HYBRID_SEARCH_WEIGHTS["keyword"]]
|
| 365 |
-
)
|
| 366 |
-
print("✅ 混合检索初始化成功")
|
| 367 |
-
except Exception as e:
|
| 368 |
-
print(f"⚠️ 混合检索初始化失败: {e}")
|
| 369 |
-
print("⚠️ 将仅使用向量检索")
|
| 370 |
-
self.ensemble_retriever = None
|
| 371 |
-
|
| 372 |
-
print(f"✅ 向量数据库创建完成并持久化到: {persist_directory}")
|
| 373 |
return self.vectorstore, self.retriever
|
| 374 |
|
| 375 |
def get_all_documents_from_vectorstore(self, limit: Optional[int] = None) -> List[Document]:
|
|
@@ -402,12 +414,63 @@ class DocumentProcessor:
|
|
| 402 |
Returns:
|
| 403 |
vectorstore, retriever, doc_splits
|
| 404 |
"""
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
|
| 409 |
-
# 返回doc_splits用于GraphRAG索引
|
| 410 |
-
return vectorstore, retriever, doc_splits
|
| 411 |
|
| 412 |
async def async_expand_query(self, query: str) -> List[str]:
|
| 413 |
"""异步扩展查询"""
|
|
|
|
| 252 |
print(f"文档分割完成,共 {len(doc_splits)} 个文档块")
|
| 253 |
return doc_splits
|
| 254 |
|
| 255 |
+
def initialize_vectorstore(self):
|
| 256 |
+
"""初始化向量数据库连接"""
|
| 257 |
+
if self.vectorstore:
|
| 258 |
+
return
|
| 259 |
+
|
| 260 |
+
print("正在连接向量数据库...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
|
| 262 |
# 强制使用 Milvus
|
| 263 |
try:
|
| 264 |
# 准备连接参数
|
| 265 |
connection_args = {}
|
| 266 |
|
| 267 |
+
# 优先使用 URI
|
|
|
|
| 268 |
if MILVUS_URI and len(MILVUS_URI.strip()) > 0:
|
|
|
|
| 269 |
is_local_file = not (MILVUS_URI.startswith("http://") or MILVUS_URI.startswith("https://"))
|
| 270 |
mode_name = "Lite (Local File)" if is_local_file else "Cloud (HTTP)"
|
|
|
|
| 271 |
print(f"🔄 正在连接 Milvus {mode_name} ({MILVUS_URI})...")
|
| 272 |
connection_args["uri"] = MILVUS_URI
|
|
|
|
|
|
|
| 273 |
if not is_local_file and MILVUS_PASSWORD:
|
| 274 |
connection_args["token"] = MILVUS_PASSWORD
|
| 275 |
else:
|
|
|
|
| 276 |
print(f"🔄 正在连接 Milvus Server ({MILVUS_HOST}:{MILVUS_PORT})...")
|
| 277 |
connection_args = {
|
| 278 |
"host": MILVUS_HOST,
|
|
|
|
| 281 |
"password": MILVUS_PASSWORD
|
| 282 |
}
|
| 283 |
|
| 284 |
+
# 初始化 Milvus 连接 (不删除旧数据)
|
| 285 |
+
self.vectorstore = Milvus(
|
| 286 |
+
embedding_function=self.embeddings,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
collection_name=COLLECTION_NAME,
|
| 288 |
connection_args=connection_args,
|
| 289 |
index_params={
|
|
|
|
| 295 |
"metric_type": "L2",
|
| 296 |
"params": MILVUS_SEARCH_PARAMS
|
| 297 |
},
|
| 298 |
+
drop_old=False, # ✅ 持久化关键:不删除旧索引
|
| 299 |
+
auto_id=True
|
| 300 |
)
|
| 301 |
+
print("✅ Milvus 向量数据库连接成功")
|
| 302 |
except ImportError:
|
| 303 |
print("❌ 未安装 pymilvus,请运行: pip install pymilvus")
|
| 304 |
raise
|
| 305 |
except Exception as e:
|
| 306 |
print(f"❌ Milvus 连接失败: {e}")
|
| 307 |
+
raise
|
| 308 |
+
|
| 309 |
+
# 配置检索器
|
|
|
|
|
|
|
| 310 |
retriever_kwargs = {}
|
| 311 |
# if ENABLE_MULTIMODAL:
|
|
|
|
|
|
|
| 312 |
# retriever_kwargs["expr"] = "data_type == 'text'"
|
|
|
|
| 313 |
self.retriever = self.vectorstore.as_retriever(search_kwargs=retriever_kwargs)
|
| 314 |
+
|
| 315 |
+
def check_existing_urls(self, urls: List[str]) -> set:
|
| 316 |
+
"""检查哪些URL已经存在于向量库中"""
|
| 317 |
+
if not self.vectorstore:
|
| 318 |
+
return set()
|
| 319 |
+
|
| 320 |
+
existing = set()
|
| 321 |
+
print("正在检查已存在的文档...")
|
| 322 |
+
try:
|
| 323 |
+
# 尝试通过检索来检查
|
| 324 |
+
# 注意:这里假设 source 字段可以作为过滤条件
|
| 325 |
+
for url in urls:
|
| 326 |
+
# 使用 similarity_search 但带有严格过滤,且只取1条
|
| 327 |
+
# 这里的 query 没关系,主要看 filter
|
| 328 |
+
try:
|
| 329 |
+
# 注意:Milvus 的 expr 语法
|
| 330 |
+
expr = f'source == "{url}"'
|
| 331 |
+
res = self.vectorstore.similarity_search(
|
| 332 |
+
"test",
|
| 333 |
+
k=1,
|
| 334 |
+
expr=expr
|
| 335 |
+
)
|
| 336 |
+
if res:
|
| 337 |
+
existing.add(url)
|
| 338 |
+
except Exception as e:
|
| 339 |
+
# 如果失败,可能是 schema 问题,尝试 metadata 字段
|
| 340 |
+
try:
|
| 341 |
+
expr = f'metadata["source"] == "{url}"'
|
| 342 |
+
res = self.vectorstore.similarity_search(
|
| 343 |
+
"test",
|
| 344 |
+
k=1,
|
| 345 |
+
expr=expr
|
| 346 |
+
)
|
| 347 |
+
if res:
|
| 348 |
+
existing.add(url)
|
| 349 |
+
except:
|
| 350 |
+
pass
|
| 351 |
+
|
| 352 |
+
print(f"✅ 发现 {len(existing)} 个已存在的 URL")
|
| 353 |
+
except Exception as e:
|
| 354 |
+
print(f"⚠️ 检查现有URL失败: {e}")
|
| 355 |
+
|
| 356 |
+
return existing
|
| 357 |
+
|
| 358 |
+
def add_documents_to_vectorstore(self, doc_splits):
|
| 359 |
+
"""添加文档到向量库"""
|
| 360 |
+
if not doc_splits:
|
| 361 |
+
return
|
| 362 |
+
|
| 363 |
+
print(f"正在添加 {len(doc_splits)} 个文档块到向量数据库...")
|
| 364 |
+
if not self.vectorstore:
|
| 365 |
+
self.initialize_vectorstore()
|
| 366 |
+
|
| 367 |
+
# 添加元数据
|
| 368 |
+
for doc in doc_splits:
|
| 369 |
+
if 'source_type' not in doc.metadata:
|
| 370 |
+
source = doc.metadata.get('source', '')
|
| 371 |
+
if any(fmt in source.lower() for fmt in SUPPORTED_IMAGE_FORMATS):
|
| 372 |
+
doc.metadata['data_type'] = 'image'
|
| 373 |
+
else:
|
| 374 |
+
doc.metadata['data_type'] = 'text'
|
| 375 |
+
|
| 376 |
+
self.vectorstore.add_documents(doc_splits)
|
| 377 |
+
print("✅ 文档添加完成")
|
| 378 |
|
| 379 |
+
def create_vectorstore(self, doc_splits, persist_directory=None):
|
| 380 |
+
"""(已弃用) 兼容旧接口,但使用新逻辑"""
|
| 381 |
+
print("⚠️ create_vectorstore 已弃用,请使用 initialize_vectorstore 和 add_documents_to_vectorstore")
|
| 382 |
+
self.initialize_vectorstore()
|
| 383 |
+
if doc_splits:
|
| 384 |
+
self.add_documents_to_vectorstore(doc_splits)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
return self.vectorstore, self.retriever
|
| 386 |
|
| 387 |
def get_all_documents_from_vectorstore(self, limit: Optional[int] = None) -> List[Document]:
|
|
|
|
| 414 |
Returns:
|
| 415 |
vectorstore, retriever, doc_splits
|
| 416 |
"""
|
| 417 |
+
if urls is None:
|
| 418 |
+
urls = KNOWLEDGE_BASE_URLS
|
| 419 |
+
|
| 420 |
+
# 1. 初始化向量库连接
|
| 421 |
+
self.initialize_vectorstore()
|
| 422 |
+
|
| 423 |
+
# 2. 检查已存在的 URL (去重)
|
| 424 |
+
existing_urls = self.check_existing_urls(urls)
|
| 425 |
+
new_urls = [url for url in urls if url not in existing_urls]
|
| 426 |
+
|
| 427 |
+
doc_splits = []
|
| 428 |
+
if new_urls:
|
| 429 |
+
print(f"🔄 发现 {len(new_urls)} 个新 URL,开始处理...")
|
| 430 |
+
docs = self.load_documents(new_urls)
|
| 431 |
+
doc_splits = self.split_documents(docs)
|
| 432 |
+
self.add_documents_to_vectorstore(doc_splits)
|
| 433 |
+
else:
|
| 434 |
+
print("✅ 所有 URL 已存在,跳过文档加载和向量化")
|
| 435 |
+
|
| 436 |
+
# 3. 初始化混合检索 (BM25)
|
| 437 |
+
if ENABLE_HYBRID_SEARCH:
|
| 438 |
+
print("正在初始化混合检索 (BM25)...")
|
| 439 |
+
try:
|
| 440 |
+
bm25_docs = []
|
| 441 |
+
# 如果有旧数据且这次没有加载全部数据,必须从 DB 加载所有文档以重建 BM25
|
| 442 |
+
# 注意:如果只有新文档,BM25 只会包含新文档,这是不对的。
|
| 443 |
+
# 只要有 existing_urls,说明库里有旧数据。
|
| 444 |
+
if len(existing_urls) > 0:
|
| 445 |
+
print("🔄 正在从向量库加载所有文档以重建 BM25 索引...")
|
| 446 |
+
# 注意:这里假设内存够大
|
| 447 |
+
all_docs = self.get_all_documents_from_vectorstore()
|
| 448 |
+
bm25_docs = all_docs
|
| 449 |
+
else:
|
| 450 |
+
# 全新构建
|
| 451 |
+
bm25_docs = doc_splits
|
| 452 |
+
|
| 453 |
+
if bm25_docs:
|
| 454 |
+
self.bm25_retriever = BM25Retriever.from_documents(
|
| 455 |
+
bm25_docs,
|
| 456 |
+
k=KEYWORD_SEARCH_K,
|
| 457 |
+
k1=BM25_K1,
|
| 458 |
+
b=BM25_B
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
self.ensemble_retriever = CustomEnsembleRetriever(
|
| 462 |
+
retrievers=[self.retriever, self.bm25_retriever],
|
| 463 |
+
weights=[HYBRID_SEARCH_WEIGHTS["vector"], HYBRID_SEARCH_WEIGHTS["keyword"]]
|
| 464 |
+
)
|
| 465 |
+
print("✅ 混合检索初始化成功")
|
| 466 |
+
else:
|
| 467 |
+
print("⚠️ 没有文档用于初始化 BM25")
|
| 468 |
+
except Exception as e:
|
| 469 |
+
print(f"⚠️ 混合检索初始化失败: {e}")
|
| 470 |
+
self.ensemble_retriever = None
|
| 471 |
|
| 472 |
+
# 返回 doc_splits用于GraphRAG索引 (注意:这里只返回了新增的)
|
| 473 |
+
return self.vectorstore, self.retriever, doc_splits
|
| 474 |
|
| 475 |
async def async_expand_query(self, query: str) -> List[str]:
|
| 476 |
"""异步扩展查询"""
|