#!/usr/bin/env python # -*- coding: utf-8 -*- """ RAG库内容查看工具 使用方法:python view_rag.py 如果遇到网络问题无法下载模型,脚本会自动尝试使用HF镜像或离线模式 """ import sys import os from pathlib import Path # 设置HuggingFace镜像(解决国内网络问题) os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com' # 添加项目路径 project_root = Path(__file__).parent sys.path.insert(0, str(project_root)) def try_load_model_with_mirror(): """ 尝试通过镜像加载模型 返回: EmbeddingModel实例 或 None """ try: from rag.embedding_model import EmbeddingModel print("正在加载嵌入模型(使用HF镜像)...") model = EmbeddingModel() if model.model is not None: print("✅ 嵌入模型加载成功") return model else: print("⚠️ 嵌入模型初始化失败,将使用离线模式") return None except Exception as e: print(f"⚠️ 无法加载嵌入模型:{e}") print("将尝试离线模式...") return None def view_rag_offline(index_path: str): """ 离线模式查看RAG库(不加载嵌入模型) 参数: index_path: 索引文件路径 """ print() print("=" * 70) print("离线模式:仅查看指标列表(不加载嵌入模型)") print("=" * 70) print() try: import json import faiss # 加载FAISS索引 print(f"正在加载索引:{index_path}") index = faiss.read_index(index_path) print(f"✅ FAISS索引加载成功") print(f" 向量数量:{index.ntotal}") print(f" 向量维度:{index.d}") print() # 尝试加载指标数据(支持多种格式) index_dir = Path(index_path).parent possible_indicator_files = [ index_dir / "indicators_metadata.json", index_dir / "indicators.pkl", Path(index_path.replace('.bin', '_indicators.json')), Path(index_path.replace('.bin', '_indicators.pkl')), ] indicators = None for ind_file in possible_indicator_files: if ind_file.exists(): print(f"正在加载指标数据:{ind_file}") if ind_file.suffix == '.json': with open(ind_file, 'r', encoding='utf-8') as f: indicators = json.load(f) elif ind_file.suffix == '.pkl': import pickle with open(ind_file, 'rb') as f: indicators = pickle.load(f) print(f"✅ 指标数据加载成功") break if indicators is None: print(f"⚠️ 未找到指标数据文件") print(f" 已搜索:") for f in possible_indicator_files: print(f" - {f}") return print(f" 指标数量:{len(indicators)}") print() # 显示指标列表 print("=" * 70) print("指标列表") print("=" * 70) print() for i, ind in enumerate(indicators, 1): name = ind.get('name', '未命名') description = ind.get('description', '无描述') business_domain = ind.get('business_domain', '未知领域') if len(description) > 80: description = description[:80] + "..." print(f"{i}. {name}") print(f" 领域:{business_domain}") print(f" 描述:{description}") print() except Exception as e: print(f"❌ 离线模式失败:{e}") import traceback traceback.print_exc() def main(): """主函数:查看RAG库中的所有指标""" print("=" * 70) print("RAG库内容查看工具") print("=" * 70) print() # 1. 检查索引文件是否存在 # 注意:索引文件可能在 data/ 或 data/vector_store/ 目录下 possible_paths = [ project_root / "data" / "faiss_index.bin", project_root / "data" / "vector_store" / "faiss_index.bin", ] index_path = None for path in possible_paths: if path.exists(): index_path = path break if index_path is None: print("❌ 索引文件不存在!") print("预期路径之一:") for path in possible_paths: print(f" - {path}") print() print("可能的原因:") print(" 1. RAG库尚未构建") print(" 2. 索引文件路径不正确") print() print("解决方法:") print(" 运行一次Streamlit应用,让系统自动构建RAG库:") print(" python -m streamlit run app.py") print(" 然后在Step 1输入任意需求,点击'理解需求'") return print(f"找到索引文件:{index_path}") print() # 2. 尝试加载嵌入模型 embedding_model = try_load_model_with_mirror() # 3. 如果模型加载失败,使用离线模式 if embedding_model is None: view_rag_offline(str(index_path)) return # 4. 模型加载成功,正常查看 try: from rag.vector_store import VectorStore print("正在加载向量存储...") vector_store = VectorStore(embedding_model) vector_store.load_index(str(index_path)) print("✅ 向量存储加载成功") print() except Exception as e: print(f"❌ 加载向量存储失败:{e}") print() print("切换到离线模式...") view_rag_offline(str(index_path)) return # 5. 显示统计信息 print("=" * 70) print("RAG库统计信息") print("=" * 70) print(f"指标总数:{len(vector_store.indicators)}") print(f"向量维度:{vector_store.dimension}") print() if len(vector_store.indicators) == 0: print("⚠️ RAG库为空,没有指标数据") return # 6. 列出所有指标 print("=" * 70) print("指标列表") print("=" * 70) print() for i, indicator in enumerate(vector_store.indicators, 1): # 获取指标信息 name = indicator.get('name', '未命名') description = indicator.get('description', '无描述') business_domain = indicator.get('business_domain', '未知领域') calculation_method = indicator.get('calculation_method', '未知') data_type = indicator.get('data_type', '未知') # 截断过长描述 if len(description) > 80: description = description[:80] + "..." # 打印指标信息 print(f"{i}. {name}") print(f" 领域:{business_domain}") print(f" 类型:{data_type}") print(f" 描述:{description}") print(f" 计算方法:{calculation_method}") print() # 7. 测试检索功能 print("=" * 70) print("检索功能测试") print("=" * 70) print() test_queries = ["销售", "用户", "分析", "指标"] for query in test_queries: try: results = vector_store.search(query, k=3) print(f"查询:{query}") if len(results) == 0: print(" ⚠️ 没有检索到结果") else: for j, (ind, score) in enumerate(results, 1): ind_name = ind.get('name', '未命名') print(f" Top{j}:{ind_name} (相似度: {score:.3f})") print() except Exception as e: print(f"查询:{query}") print(f" ❌ 检索失败:{e}") print() print("=" * 70) print("查看完成!") print("=" * 70) if __name__ == "__main__": main()