Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
11 KiB
11 KiB
文件加载模块调试指南
📋 模块概述
文件加载模块负责从各种文件格式中加载文档内容,是 RAG 评估框架的基础组件。
核心组件
- document_loader.py - 文档加载器
- sampling.py - 采样策略
- generator.py - 测评集生成器
- validator.py - 测评集验证器
🎯 调试入口点
主要入口函数
# 1. 加载单个文件
from rag_evaluation.testset.document_loader import TextLoader, MarkdownLoader
loader = TextLoader("path/to/file.txt")
documents = loader.load()
# 2. 批量加载文件
from rag_evaluation.testset.document_loader import load_documents
documents = load_documents([
"file1.txt",
"file2.md",
"file3.markdown"
])
# 3. 文档采样
from rag_evaluation.testset.sampling import SamplingStrategy
from rag_evaluation.core.config import TestsetConfig
config = TestsetConfig()
sampler = SamplingStrategy(config)
sampled_docs = sampler.sample_documents(documents)
# 4. 文档分块
from rag_evaluation.testset.sampling import DocumentChunker
chunker = DocumentChunker(chunk_size=1000, chunk_overlap=200)
chunks = chunker.chunk_documents(documents)
🔍 关键代码位置
1. 文档加载器 (document_loader.py)
核心类:
Document(第 10-15 行) - 文档数据结构DocumentLoader(第 18-36 行) - 基础加载器TextLoader(第 39-53 行) - 文本文件加载器MarkdownLoader(第 56-70 行) - Markdown 文件加载器
关键方法:
load()- 加载文档内容get_file_size()- 获取文件大小get_file_extension()- 获取文件扩展名
入口函数:
load_documents()(第 73-100 行) - 批量加载文档
2. 采样策略 (sampling.py)
核心类:
SamplingStrategy(第 11-66 行) - 采样策略DocumentChunker(第 69-133 行) - 文档分块器
关键方法:
get_sampling_rate()(第 22-39 行) - 计算采样率sample_documents()(第 41-66 行) - 执行采样chunk_document()(第 83-115 行) - 分块单个文档chunk_documents()(第 117-133 行) - 批量分块
🧪 测试文件
test_document_loader.py
测试类:
TestDocument- 测试 Document 类TestDocumentLoader- 测试基础加载器TestTextLoader- 测试文本加载器TestMarkdownLoader- 测试 Markdown 加载器TestLoadDocuments- 测试批量加载
运行测试:
cd rag_evaluation
python -m pytest tests/test_document_loader.py -v
test_sampling.py
运行测试:
cd rag_evaluation
python -m pytest tests/test_sampling.py -v
🐛 调试步骤
步骤 1: 准备测试数据
创建测试文件:
cd rag_evaluation
# 创建测试目录
mkdir -p test_data
# 创建测试文件
echo "这是一个测试文本文件" > test_data/test.txt
echo "# 测试 Markdown\n\n这是测试内容" > test_data/test.md
步骤 2: 创建调试脚本
创建 debug_loader.py:
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from testset.document_loader import load_documents
from testset.sampling import SamplingStrategy, DocumentChunker
from core.config import TestsetConfig
def debug_document_loading():
"""调试文档加载"""
print("=" * 60)
print("调试: 文档加载")
print("=" * 60)
# 1. 加载文档
file_paths = [
"test_data/test.txt",
"test_data/test.md"
]
print(f"\n加载文件: {file_paths}")
try:
documents = load_documents(file_paths)
print(f"✓ 成功加载 {len(documents)} 个文档")
for i, doc in enumerate(documents):
print(f"\n文档 {i+1}:")
print(f" - 来源: {doc.metadata.get('source')}")
print(f" - 类型: {doc.metadata.get('file_type')}")
print(f" - 大小: {doc.metadata.get('file_size')} 字节")
print(f" - 内容长度: {len(doc.page_content)} 字符")
print(f" - 内容预览: {doc.page_content[:100]}...")
except Exception as e:
print(f"✗ 加载失败: {e}")
import traceback
traceback.print_exc()
return None
return documents
def debug_sampling(documents):
"""调试采样策略"""
print("\n" + "=" * 60)
print("调试: 采样策略")
print("=" * 60)
config = TestsetConfig()
sampler = SamplingStrategy(config)
print(f"\n采样配置:")
print(f" - 小文件阈值: {config.sampling_strategy['small_file_threshold_mb']} MB")
print(f" - 中文件阈值: {config.sampling_strategy['medium_file_threshold_mb']} MB")
print(f" - 小文件采样率: {config.sampling_strategy['small_file_sampling_rate']}")
print(f" - 中文件采样率: {config.sampling_strategy['medium_file_sampling_rate']}")
print(f" - 大文件采样率: {config.sampling_strategy['large_file_sampling_rate']}")
try:
sampled_docs = sampler.sample_documents(documents)
print(f"\n✓ 采样完成: {len(sampled_docs)}/{len(documents)} 文档")
for i, doc in enumerate(sampled_docs):
file_size = doc.metadata.get('file_size', 0)
sampling_rate = sampler.get_sampling_rate(file_size)
print(f" 文档 {i+1}: 采样率 = {sampling_rate:.2f}")
except Exception as e:
print(f"✗ 采样失败: {e}")
import traceback
traceback.print_exc()
return None
return sampled_docs
def debug_chunking(documents):
"""调试文档分块"""
print("\n" + "=" * 60)
print("调试: 文档分块")
print("=" * 60)
chunker = DocumentChunker(chunk_size=100, chunk_overlap=20)
print(f"\n分块配置:")
print(f" - 块大小: {chunker.chunk_size} 字符")
print(f" - 重叠大小: {chunker.chunk_overlap} 字符")
try:
chunks = chunker.chunk_documents(documents)
print(f"\n✓ 分块完成: {len(chunks)} 个块")
for i, chunk in enumerate(chunks[:5]): # 只显示前5个
print(f"\n 块 {i+1}:")
print(f" - 来源: {chunk.metadata.get('source')}")
print(f" - 块索引: {chunk.metadata.get('chunk_index')}")
print(f" - 起始位置: {chunk.metadata.get('chunk_start')}")
print(f" - 结束位置: {chunk.metadata.get('chunk_end')}")
print(f" - 内容长度: {len(chunk.page_content)} 字符")
print(f" - 内容预览: {chunk.page_content[:50]}...")
if len(chunks) > 5:
print(f"\n ... 还有 {len(chunks) - 5} 个块")
except Exception as e:
print(f"✗ 分块失败: {e}")
import traceback
traceback.print_exc()
return None
return chunks
def main():
"""主函数"""
print("\n" + "=" * 60)
print("文件加载模块调试")
print("=" * 60)
# 1. 调试文档加载
documents = debug_document_loading()
if not documents:
print("\n调试终止: 文档加载失败")
return
# 2. 调试采样
sampled_docs = debug_sampling(documents)
if not sampled_docs:
print("\n调试终止: 采样失败")
return
# 3. 调试分块
chunks = debug_chunking(sampled_docs)
if not chunks:
print("\n调试终止: 分块失败")
return
print("\n" + "=" * 60)
print("调试完成!")
print("=" * 60)
print(f"\n总结:")
print(f" - 加载文档: {len(documents)} 个")
print(f" - 采样后: {len(sampled_docs)} 个")
print(f" - 分块后: {len(chunks)} 个")
print()
if __name__ == '__main__':
main()
步骤 3: 运行调试脚本
cd rag_evaluation
python debug_loader.py
步骤 4: 使用 Python 调试器
使用 pdb 进行交互式调试:
# 在代码中添加断点
import pdb; pdb.set_trace()
# 或使用 IPython
from IPython import embed; embed()
使用 VS Code 调试:
- 创建
.vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Document Loader",
"type": "debugpy",
"request": "launch",
"program": "${workspaceFolder}/rag_evaluation/debug_loader.py",
"console": "integratedTerminal",
"cwd": "${workspaceFolder}/rag_evaluation"
}
]
}
- 在代码中设置断点
- 按 F5 开始调试
🔧 常见问题排查
问题 1: FileNotFoundError
症状: 文件找不到
排查:
from pathlib import Path
file_path = "test_data/test.txt"
path = Path(file_path)
print(f"文件路径: {path}")
print(f"绝对路径: {path.absolute()}")
print(f"文件存在: {path.exists()}")
print(f"是文件: {path.is_file()}")
问题 2: UnicodeDecodeError
症状: 编码错误
排查:
# 检测文件编码
import chardet
with open(file_path, 'rb') as f:
raw_data = f.read()
result = chardet.detect(raw_data)
print(f"检测到的编码: {result['encoding']}")
print(f"置信度: {result['confidence']}")
问题 3: 采样率计算错误
症状: 采样结果不符合预期
排查:
from utils.helpers import calculate_file_size_mb
file_size_bytes = 1024 * 1024 * 5 # 5MB
file_size_mb = calculate_file_size_mb(file_size_bytes)
print(f"文件大小: {file_size_bytes} 字节")
print(f"文件大小: {file_size_mb} MB")
sampler = SamplingStrategy(config)
sampling_rate = sampler.get_sampling_rate(file_size_bytes)
print(f"采样率: {sampling_rate}")
问题 4: 分块重叠错误
症状: 分块边界不正确
排查:
chunker = DocumentChunker(chunk_size=100, chunk_overlap=20)
# 测试小文档
test_content = "A" * 250 # 250个字符
test_doc = Document(content=test_content, metadata={})
chunks = chunker.chunk_document(test_doc)
print(f"原始长度: {len(test_content)}")
print(f"块数量: {len(chunks)}")
for i, chunk in enumerate(chunks):
start = chunk.metadata['chunk_start']
end = chunk.metadata['chunk_end']
print(f"块 {i}: [{start}:{end}] 长度={len(chunk.page_content)}")
📊 性能分析
使用 cProfile
import cProfile
import pstats
profiler = cProfile.Profile()
profiler.enable()
# 执行要分析的代码
documents = load_documents(file_paths)
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(20) # 显示前20个最耗时的函数
使用 memory_profiler
pip install memory-profiler
# 在函数上添加装饰器
@profile
def load_documents(file_paths):
...
# 运行
python -m memory_profiler debug_loader.py
📝 日志配置
添加详细日志:
import logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('debug_loader.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# 在代码中添加日志
logger.debug(f"加载文件: {file_path}")
logger.info(f"成功加载 {len(documents)} 个文档")
logger.warning(f"文件大小超过阈值: {file_size_mb} MB")
logger.error(f"加载失败: {e}")
🎓 下一步
调试完文件加载模块后,可以继续调试:
- 测评集生成器 (
generator.py) - 测评集验证器 (
validator.py) - 评估执行引擎 (
evaluation/executor.py) - 指标计算器 (
evaluation/metrics.py)
📚 参考资料
- 测试文件:
tests/test_document_loader.py - 测试文件:
tests/test_sampling.py - 配置文件:
core/config.py - 工具函数:
utils/helpers.py