Spaces:
Runtime error

File size: 8,200 Bytes
ce06eb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
#!/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()