first commit
This commit is contained in:
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
BM25 关键词检索索引管理
|
||||
|
||||
负责 jieba 分词 → 去停用词 → 构建 bm25s 索引 → 保存/加载 → 一致性校验。
|
||||
每次向量库写操作后调用 rebuild() 重建索引。
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from typing import List, Tuple, Optional
|
||||
|
||||
import bm25s
|
||||
import jieba
|
||||
|
||||
from app.config import settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 加载中文停用词
|
||||
_stopwords: set = set()
|
||||
try:
|
||||
import importlib
|
||||
_sw_module = importlib.import_module("app.core.stopwords-zh")
|
||||
_stopwords = set(_sw_module.STOPWORDS_CHINESE)
|
||||
except ImportError:
|
||||
logger.warning("stopwords_zh not found, BM25 will not filter stopwords")
|
||||
|
||||
|
||||
def _tokenize(text: str) -> List[str]:
|
||||
"""jieba 分词 + 去停用词"""
|
||||
tokens = jieba.lcut(text)
|
||||
return [t for t in tokens if t.strip() and t not in _stopwords]
|
||||
|
||||
|
||||
class Bm25Index:
|
||||
"""单个 BM25 索引的管理器(knowledge 或 questions)"""
|
||||
|
||||
def __init__(self, index_name: str):
|
||||
"""
|
||||
Args:
|
||||
index_name: 索引名称,如 "knowledge" 或 "questions",用于子目录名
|
||||
"""
|
||||
self._index_name = index_name
|
||||
self._index_dir = os.path.join(settings.bm25_index_path, index_name)
|
||||
self._version_file = os.path.join(self._index_dir, "version.json")
|
||||
self._retriever: Optional[bm25s.BM25] = None
|
||||
os.makedirs(self._index_dir, exist_ok=True)
|
||||
|
||||
@property
|
||||
def retriever(self) -> bm25s.BM25:
|
||||
"""懒加载:有索引就用,没有就返回空 BM25"""
|
||||
if self._retriever is None:
|
||||
self._retriever = bm25s.BM25()
|
||||
return self._retriever
|
||||
|
||||
def rebuild(self, doc_ids: List[str], texts: List[str]) -> None:
|
||||
"""从头重建索引:分词 → 去停用词 → 建索引 → 保存
|
||||
|
||||
Args:
|
||||
doc_ids: 文档 ID 列表(knowledge 用 chunk_id, questions 用 help_id)
|
||||
texts: 对应的文本列表(用于构建 BM25 倒排索引)
|
||||
"""
|
||||
if not doc_ids or not texts:
|
||||
logger.info(f"bm25 [{self._index_name}]: empty corpus, skip rebuild")
|
||||
return
|
||||
|
||||
logger.info(f"bm25 [{self._index_name}]: rebuilding with {len(doc_ids)} docs")
|
||||
|
||||
# jieba 分词
|
||||
corpus_tokens = [_tokenize(t) for t in texts]
|
||||
|
||||
# 构建索引
|
||||
self._retriever = bm25s.BM25()
|
||||
self._retriever.index(corpus_tokens)
|
||||
|
||||
# 保存索引(corpus 存为 [{doc_id: ...}],语义明确,检索时可直接取 doc_id 键)
|
||||
self._retriever.save(
|
||||
self._index_dir,
|
||||
corpus=[{"doc_id": d} for d in doc_ids],
|
||||
)
|
||||
# save 不会设置内存中的 corpus,这里手动补上,保证重建后立即可检索到 doc_id
|
||||
self._retriever.corpus = [{"doc_id": d} for d in doc_ids]
|
||||
|
||||
# 保存版本文件
|
||||
self._save_version(doc_ids)
|
||||
|
||||
logger.info(f"bm25 [{self._index_name}]: rebuild complete, saved to {self._index_dir}")
|
||||
|
||||
def search(self, query: str, top_k: int = 5) -> List[Tuple[str, float]]:
|
||||
"""关键词搜索,返回 (doc_id, score) 列表
|
||||
|
||||
Args:
|
||||
query: 查询文本
|
||||
top_k: 返回数量
|
||||
|
||||
Returns:
|
||||
[(doc_id, score), ...] 按分数降序
|
||||
"""
|
||||
if self._retriever is None or not self._has_index():
|
||||
return []
|
||||
|
||||
# bm25s 要求 k <= corpus 大小,否则 retrieve 抛异常导致整路检索丢失;
|
||||
# 这里把 k 钳制到实际 corpus 大小(corpus 为 [{doc_id: ...}] 列表)
|
||||
corpus_size = len(self._retriever.corpus) if self._retriever.corpus is not None else 0
|
||||
k = min(top_k, corpus_size)
|
||||
if k <= 0:
|
||||
return []
|
||||
|
||||
query_tokens = [_tokenize(query)]
|
||||
try:
|
||||
results, scores = self._retriever.retrieve(query_tokens, k=k)
|
||||
except Exception as e:
|
||||
logger.warning(f"bm25 [{self._index_name}] search failed: {e}")
|
||||
return []
|
||||
|
||||
# results shape: (1, k), scores shape: (1, k)
|
||||
out = []
|
||||
for i in range(results.shape[1]):
|
||||
doc_id = results[0, i]
|
||||
score = float(scores[0, i])
|
||||
# bm25s 返回的 corpus 条目是 dict,取我们自定义的 doc_id 键
|
||||
if isinstance(doc_id, dict):
|
||||
doc_id = doc_id.get("doc_id", "")
|
||||
out.append((doc_id, score))
|
||||
return out
|
||||
|
||||
def load_or_rebuild(self, vector_store_count: int, get_all_fn) -> None:
|
||||
"""启动时调用:比对 version.json 与向量库,不一致则重建
|
||||
|
||||
Args:
|
||||
vector_store_count: 向量库当前文档数
|
||||
get_all_fn: callable() -> (doc_ids: list[str], texts: list[str])
|
||||
从向量库获取全部文档 ID 和文本的回调
|
||||
"""
|
||||
saved_ids = self._load_saved_ids()
|
||||
|
||||
if saved_ids is not None and len(saved_ids) == vector_store_count:
|
||||
# 数量一致,再比对 ID 集合
|
||||
current_ids, _ = get_all_fn()
|
||||
if set(saved_ids) == set(current_ids):
|
||||
self._load_retriever()
|
||||
logger.info(f"bm25 [{self._index_name}]: loaded from cache, {len(saved_ids)} docs")
|
||||
return
|
||||
|
||||
# 不一致,重建
|
||||
logger.info(f"bm25 [{self._index_name}]: version mismatch, rebuilding...")
|
||||
doc_ids, texts = get_all_fn()
|
||||
self.rebuild(doc_ids, texts)
|
||||
|
||||
def _has_index(self) -> bool:
|
||||
"""检查索引文件是否存在"""
|
||||
return os.path.exists(os.path.join(self._index_dir, "vocab.index.json"))
|
||||
|
||||
def _load_retriever(self) -> None:
|
||||
"""从磁盘加载索引"""
|
||||
try:
|
||||
self._retriever = bm25s.BM25.load(self._index_dir, load_corpus=True)
|
||||
except Exception as e:
|
||||
logger.warning(f"bm25 [{self._index_name}]: load failed: {e}, will rebuild on next write")
|
||||
self._retriever = bm25s.BM25()
|
||||
|
||||
def _load_saved_ids(self) -> Optional[List[str]]:
|
||||
"""从 version.json 读取保存的 doc_ids,读取失败返回 None"""
|
||||
try:
|
||||
with open(self._version_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data.get("doc_ids")
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
return None
|
||||
|
||||
def _save_version(self, doc_ids: List[str]) -> None:
|
||||
"""保存版本文件:doc_ids + last_updated"""
|
||||
data = {
|
||||
"doc_ids": doc_ids,
|
||||
"last_updated": datetime.now(timezone.utc).isoformat()
|
||||
}
|
||||
with open(self._version_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
Reference in New Issue
Block a user