Spaces:
Runtime error
Runtime error
Download rag/vector_store.py from Macbath/indicator-modeling: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/spaces/Macbath/indicator-modeling/resolve/main/rag/vector_store.py
- Command line
-
hf download hf://spaces/Macbath/indicator-modeling/rag/vector_store.py
-
curl -L -o vector_store.py https://huggingface.co/spaces/Macbath/indicator-modeling/resolve/main/rag/vector_store.py
12.6 kB
| """ | |
| 向量存储模块 - 基于 FAISS 的指标检索系统 (v3.0) | |
| 本模块提供向量存储和检索功能,使用 FAISS 作为向量数据库, | |
| 结合嵌入模型实现语义相似度检索。 | |
| 主要功能: | |
| 1. 构建 FAISS 向量索引(支持从指标列表或 IndicatorSet) | |
| 2. 保存/加载索引和元数据(持久化) | |
| 3. 语义检索(根据自然语言查询找到最相关的指标) | |
| 4. 支持余弦相似度检索(内积) | |
| 技术栈: | |
| - FAISS: Facebook AI 开发的向量相似性搜索库 | |
| - SentenceTransformer: 文本嵌入模型 | |
| 典型使用场景: | |
| - 用户输入自然语言,检索最相关的业务指标 | |
| - 指标去重(查找语义相似的已有指标) | |
| - 指标推荐(根据历史查询推荐相关指标) | |
| 作者: 数据指标建模助手开发团队 | |
| 版本: 3.0 | |
| 依赖: numpy, faiss, sentence_transformers, pathlib, json | |
| """ | |
| import json | |
| import numpy as np | |
| import faiss | |
| from pathlib import Path | |
| from typing import List, Dict, Any, Tuple | |
| import logging | |
| # 导入同模块的嵌入模型(相对导入) | |
| from .embedding_model import EmbeddingModel | |
| # 配置日志记录 | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| class VectorStore: | |
| """ | |
| 向量存储类 - 基于 FAISS 的指标语义检索 | |
| 封装了 FAISS 向量索引的构建、保存、加载和检索功能。 | |
| 结合 EmbeddingModel 实现文本到向量的转换和相似度检索。 | |
| 属性: | |
| embedding_model (EmbeddingModel): 嵌入模型实例 | |
| index_path (Path): FAISS 索引保存/加载路径 | |
| index (faiss.Index): FAISS 向量索引对象 | |
| indicators (List[Dict]): 指标元数据列表(与索引向量一一对应) | |
| dimension (int): 向量维度(如 384) | |
| logger (Logger): 日志记录器 | |
| 主要功能: | |
| - 构建向量索引(从指标列表或 IndicatorSet) | |
| - 保存/加载索引到磁盘 | |
| - 语义检索(根据自然语言查询) | |
| """ | |
| def __init__(self, embedding_model: EmbeddingModel, index_path: Path = None): | |
| """ | |
| 初始化向量存储 | |
| 参数: | |
| embedding_model (EmbeddingModel): 嵌入模型实例 | |
| 用于生成文本嵌入向量 | |
| index_path (Path): FAISS 索引保存/加载路径(可选) | |
| 如果提供且索引文件存在,将自动加载 | |
| 返回: | |
| None | |
| 示例: | |
| >>> embedding_model = EmbeddingModel() | |
| >>> vector_store = VectorStore(embedding_model, Path("data/faiss.index")) | |
| """ | |
| self.embedding_model = embedding_model | |
| self.index_path = index_path | |
| self.index = None # FAISS 索引对象 | |
| self.indicators = [] # 指标元数据列表 | |
| self.dimension = None # 向量维度 | |
| # 如果提供了索引路径且索引存在,则自动加载 | |
| if index_path and index_path.exists(): | |
| self.load_index() | |
| def build_index(self, indicators: List[Dict[str, Any]]): | |
| """ | |
| 从指标列表构建 FAISS 向量索引 | |
| 核心方法:将指标数据转换为向量并构建 FAISS 索引。 | |
| 参数: | |
| indicators (List[Dict]): 指标字典列表,每个字典包含: | |
| - 'id': 指标 ID | |
| - 'name': 指标名称 | |
| - 'description': 指标描述 | |
| - 'dimensions': 维度列表 | |
| - ...(其他字段) | |
| 返回: | |
| None | |
| 处理逻辑: | |
| 1. 验证输入(指标列表不能为空) | |
| 2. 构建文本表示(名称 + 描述 + 维度) | |
| 3. 生成嵌入向量 | |
| 4. 构建 FAISS 索引(内积,用于余弦相似度) | |
| 5. 保存索引(如果提供了 index_path) | |
| 注意: | |
| - 使用内积(IndexFlatIP)+ L2 归一化 = 余弦相似度 | |
| - FAISS 需要 float32 类型 | |
| """ | |
| # 1. 验证输入 | |
| if not indicators: | |
| logger.warning("没有提供指标数据,无法构建索引") | |
| return | |
| # 保存指标元数据(与向量一一对应) | |
| self.indicators = indicators | |
| # 2. 构建文本表示(用于生成嵌入向量) | |
| texts = [] | |
| for ind in indicators: | |
| # 组合多个字段以提高检索准确性 | |
| text = f"{ind.get('name', '')} {ind.get('description', '')} {' '.join(ind.get('dimensions', []))}" | |
| texts.append(text) | |
| # 3. 生成嵌入向量 | |
| logger.info(f"正在为 {len(texts)} 个指标生成嵌入向量...") | |
| embeddings = self.embedding_model.encode(texts, show_progress_bar=True) | |
| # 确保数据类型为 float32(FAISS 要求) | |
| embeddings = embeddings.astype(np.float32) | |
| self.dimension = embeddings.shape[1] # 获取向量维度 | |
| # 4. 构建 FAISS 索引 | |
| logger.info(f"正在构建 FAISS 索引,维度: {self.dimension}...") | |
| # IndexFlatIP: 平坦内积索引(用于余弦相似度) | |
| self.index = faiss.IndexFlatIP(self.dimension) | |
| # 归一化向量(使得内积 = 余弦相似度) | |
| faiss.normalize_L2(embeddings) | |
| # 将向量添加到索引 | |
| self.index.add(embeddings) | |
| logger.info(f"FAISS 索引构建成功,包含 {self.index.ntotal} 个向量") | |
| # 5. 保存索引(如果提供了路径) | |
| if self.index_path: | |
| self.save_index() | |
| def build_index_from_indicator_set(self, indicator_set: 'IndicatorSet'): | |
| """ | |
| 从 IndicatorSet 构建 FAISS 向量索引(v3.0 兼容方法) | |
| 便捷方法:从 IndicatorSet 对象提取指标并构建索引。 | |
| 为 v3.0 版本添加,以保持接口兼容性。 | |
| 参数: | |
| indicator_set (IndicatorSet): 指标集对象 | |
| 包含多个 Indicator 对象 | |
| 返回: | |
| None | |
| 处理逻辑: | |
| 1. 验证输入(IndicatorSet 和 indicators 不能为空) | |
| 2. 将 Indicator 对象转换为字典列表 | |
| 3. 调用 build_index 方法 | |
| 示例: | |
| >>> indicator_set = IndicatorSet(...) | |
| >>> vector_store.build_index_from_indicator_set(indicator_set) | |
| """ | |
| # 1. 验证输入 | |
| if not indicator_set or not indicator_set.indicators: | |
| logger.warning("没有提供指标数据,无法构建索引") | |
| return | |
| # 2. 将 Indicator 对象转换为字典 | |
| indicators_dict = [ind.to_dict() for ind in indicator_set.indicators] | |
| logger.info(f"从 IndicatorSet 构建索引: {indicator_set.set_name} ({len(indicators_dict)} 个指标)") | |
| # 3. 调用已有的 build_index 方法 | |
| self.build_index(indicators_dict) | |
| logger.info(f"从 IndicatorSet 构建索引成功") | |
| def save_index(self): | |
| """ | |
| 保存 FAISS 索引和指标元数据到磁盘 | |
| 内部方法:将 FAISS 索引和指标元数据分别保存到文件。 | |
| 文件结构: | |
| {index_path}: FAISS 索引文件 | |
| {index_path.parent}/indicators_metadata.json: 指标元数据 JSON | |
| 返回: | |
| None | |
| 异常处理: | |
| 如果索引不存在,记录警告并返回 | |
| """ | |
| # 检查索引是否存在 | |
| if self.index is None: | |
| logger.warning("没有索引可以保存") | |
| return | |
| # 创建输出目录(如果不存在) | |
| self.index_path.parent.mkdir(parents=True, exist_ok=True) | |
| # 1. 保存 FAISS 索引到文件 | |
| faiss.write_index(self.index, str(self.index_path)) | |
| # 2. 保存指标元数据到 JSON 文件 | |
| metadata_path = self.index_path.parent / "indicators_metadata.json" | |
| with open(metadata_path, 'w', encoding='utf-8') as f: | |
| json.dump(self.indicators, f, ensure_ascii=False, indent=2) | |
| logger.info(f"索引已保存到 {self.index_path}") | |
| logger.info(f"元数据已保存到 {metadata_path}") | |
| def load_index(self): | |
| """ | |
| 从磁盘加载 FAISS 索引和指标元数据 | |
| 内部方法:从文件加载 FAISS 索引和指标元数据。 | |
| 返回: | |
| None | |
| 异常处理: | |
| 如果加载失败,将索引和元数据重置为空 | |
| 文件结构: | |
| {index_path}: FAISS 索引文件 | |
| {index_path.parent}/indicators_metadata.json: 指标元数据 JSON | |
| """ | |
| try: | |
| # 1. 加载 FAISS 索引 | |
| self.index = faiss.read_index(str(self.index_path)) | |
| # 获取向量维度(从索引对象中读取) | |
| self.dimension = self.index.d | |
| # 2. 加载指标元数据 | |
| metadata_path = self.index_path.parent / "indicators_metadata.json" | |
| with open(metadata_path, 'r', encoding='utf-8') as f: | |
| self.indicators = json.load(f) | |
| logger.info(f"索引已从 {self.index_path} 加载") | |
| logger.info(f"已加载 {self.index.ntotal} 个向量和 {len(self.indicators)} 个指标") | |
| except Exception as e: | |
| # 加载失败,重置状态 | |
| logger.error(f"加载索引失败: {e}") | |
| self.index = None | |
| self.indicators = [] | |
| def search(self, query: str, k: int = 5) -> List[Tuple[Dict[str, Any], float]]: | |
| """ | |
| 根据查询文本检索相似的指标 | |
| 核心方法:将查询文本转换为向量, | |
| 在 FAISS 索引中检索最相似的 k 个指标。 | |
| 参数: | |
| query (str): 查询文本(自然语言) | |
| k (int): 返回的最相似结果数量 | |
| 默认: 5 | |
| 返回: | |
| List[Tuple[Dict, float]]: 检索结果列表,每个元素为: | |
| (指标字典, 相似度分数) | |
| 按相似度降序排列 | |
| 处理逻辑: | |
| 1. 检查索引是否已构建 | |
| 2. 生成查询文本的嵌入向量 | |
| 3. 归一化查询向量(用于余弦相似度) | |
| 4. 在 FAISS 索引中搜索最相似的 k 个向量 | |
| 5. 构建结果列表(指标字典 + 相似度分数) | |
| 示例: | |
| >>> results = vector_store.search("每日订单金额") | |
| >>> for ind, score in results: | |
| >>> print(f"{ind['name']}: {score:.3f}") | |
| """ | |
| # 1. 检查索引是否已构建 | |
| if self.index is None or self.index.ntotal == 0: | |
| logger.warning("索引为空,请先构建或加载索引") | |
| return [] | |
| # 2. 生成查询文本的嵌入向量 | |
| query_embedding = self.embedding_model.encode_single(query) | |
| # 重塑为 2D 数组(FAISS 要求) | |
| query_embedding = query_embedding.reshape(1, -1).astype(np.float32) | |
| # 3. 归一化查询向量(使得内积 = 余弦相似度) | |
| faiss.normalize_L2(query_embedding) | |
| # 4. 在 FAISS 索引中搜索(返回最相似的 k 个结果) | |
| # scores: 相似度分数矩阵 | |
| # indices: 索引位置矩阵 | |
| scores, indices = self.index.search(query_embedding, min(k, self.index.ntotal)) | |
| # 5. 构建结果列表 | |
| results = [] | |
| # 遍历结果(scores[0] 和 indices[0] 是因为 batch size = 1) | |
| for score, idx in zip(scores[0], indices[0]): | |
| # 确保索引在有效范围内 | |
| if idx < len(self.indicators): | |
| results.append((self.indicators[idx], float(score))) | |
| return results | |
| def is_ready(self) -> bool: | |
| """ | |
| 检查向量存储是否准备好(索引已构建) | |
| 返回: | |
| bool: 如果索引已构建且包含向量,返回 True;否则返回 False | |
| 示例: | |
| >>> if vector_store.is_ready(): | |
| >>> results = vector_store.search("查询文本") | |
| """ | |
| return self.index is not None and self.index.ntotal > 0 | |