新增功能: - ✅ 实时进度跟踪:进度条、ETA、已用时间 - ✅ 滚动更新:每完成一个问题就保存结果 - ✅ 原子写入:防止文件损坏 新增文件: - src/utils/progress_tracker.py - 进度跟踪器 - 可视化进度条 - ETA 预估(基于实际耗时) - 各指标平均耗时统计 - docs/ROLLING_UPDATE_GUIDE.md - 滚动更新使用指南 - 功能说明和使用场景 - 文件格式详解 - 最佳实践 修改文件: - src/evaluators/configurable_evaluator.py - 集成 ProgressTracker - 实现 _init_output_file() 初始化输出文件 - 实现 _update_output_file() 滚动更新 - 支持原子写入(临时文件 + 重命名) - scripts/evaluate_with_config.py - 添加 --output 参数支持滚动更新 - 添加 show_progress 选项 - 更新帮助文档和示例 - scripts/evaluate_all_types_advanced.bat - 添加滚动更新选项 - 自动生成带时间戳的输出目录 - 更新总结信息显示配置 - docs/progress/TODO.md - 更新版本到 v2.1.1 - 记录用户体验优化功能 技术亮点: - 原子写入保证文件完整性 - 实时进度显示(进度条、ETA) - 滚动更新防止数据丢失 - 用户体验大幅提升 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
345 lines
11 KiB
Python
345 lines
11 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
可配置系统评估脚本
|
||
|
||
支持通过参数启用/禁用特定评估指标,灵活控制评估速度和质量
|
||
"""
|
||
import sys
|
||
import os
|
||
import asyncio
|
||
import argparse
|
||
from pathlib import Path
|
||
from datetime import datetime
|
||
|
||
# 设置 Windows 控制台编码为 UTF-8
|
||
if sys.platform == 'win32':
|
||
import io
|
||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
|
||
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
|
||
|
||
# 添加项目根目录到 Python 路径
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
|
||
async def evaluate_system(
|
||
system: str,
|
||
test_set_path: str,
|
||
enable_parallel: bool = True,
|
||
enable_logging: bool = True,
|
||
disabled_metrics: list = None,
|
||
enabled_metrics: list = None,
|
||
output_file: str = None
|
||
):
|
||
"""
|
||
评估单个系统
|
||
|
||
Args:
|
||
system: 系统名称
|
||
test_set_path: 测试集路径
|
||
enable_parallel: 是否启用并行评估
|
||
enable_logging: 是否启用详细日志
|
||
disabled_metrics: 要禁用的指标列表
|
||
enabled_metrics: 要启用的指标列表(优先级更高)
|
||
output_file: 输出文件路径(如果提供,将实现滚动更新)
|
||
"""
|
||
from src.transformers.data_converter import DataConverter
|
||
from src.evaluators.configurable_evaluator import ConfigurableRAGAsEvaluator
|
||
from src.utils.evaluation_logger import EvaluationLogger
|
||
from src.reporters.json_reporter import JSONReporter
|
||
|
||
print()
|
||
print("=" * 80)
|
||
print(f"评估系统: {system.upper()}")
|
||
print("=" * 80)
|
||
print()
|
||
|
||
# 转换为集合
|
||
disabled_set = set(disabled_metrics) if disabled_metrics else None
|
||
enabled_set = set(enabled_metrics) if enabled_metrics else None
|
||
|
||
# 创建日志记录器
|
||
logger = EvaluationLogger(system_name=system) if enable_logging else None
|
||
|
||
if logger:
|
||
print(f"日志文件: {logger.get_log_file_path()}")
|
||
print()
|
||
|
||
start_time = datetime.now()
|
||
print(f"开始时间: {start_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
||
print(f"并行模式: {'启用' if enable_parallel else '禁用'}")
|
||
print()
|
||
|
||
try:
|
||
# 创建数据转换器
|
||
converter = DataConverter(test_set_path)
|
||
|
||
# 加载并转换数据
|
||
print("[1/3] 加载并转换数据...")
|
||
positive_cases, negative_cases = converter.merge_data_for_system(system)
|
||
|
||
print(f" - 正向用例: {len(positive_cases)}")
|
||
print(f" - 负向用例: {len(negative_cases)}")
|
||
print()
|
||
|
||
# 创建可配置评估器
|
||
print("[配置] 初始化评估器...")
|
||
evaluator = ConfigurableRAGAsEvaluator(
|
||
logger=logger,
|
||
enable_parallel=enable_parallel,
|
||
disabled_metrics=disabled_set,
|
||
enabled_metrics=enabled_set,
|
||
show_progress=True
|
||
)
|
||
print()
|
||
|
||
# 准备输出文件路径
|
||
positive_output_file = None
|
||
negative_output_file = None
|
||
if output_file:
|
||
output_path = Path(output_file)
|
||
positive_output_file = str(output_path.parent / f"{output_path.stem}_positive{output_path.suffix}")
|
||
negative_output_file = str(output_path.parent / f"{output_path.stem}_negative{output_path.suffix}")
|
||
|
||
# 评估正向用例
|
||
print(f"[2/3] 评估正向用例...")
|
||
positive_results = await evaluator.evaluate_batch(
|
||
positive_cases,
|
||
output_file=positive_output_file
|
||
)
|
||
print()
|
||
|
||
# 评估负向用例
|
||
print(f"[3/3] 评估负向用例...")
|
||
negative_results = await evaluator.evaluate_batch(
|
||
negative_cases,
|
||
output_file=negative_output_file
|
||
)
|
||
print()
|
||
|
||
end_time = datetime.now()
|
||
duration = (end_time - start_time).total_seconds()
|
||
|
||
print()
|
||
print("=" * 80)
|
||
print("✅ 评估完成!")
|
||
print("=" * 80)
|
||
print(f"结束时间: {end_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
||
print(f"总耗时: {duration:.2f} 秒 ({duration/60:.1f} 分钟)")
|
||
print()
|
||
|
||
# 构建结果
|
||
result = {
|
||
'system': system,
|
||
'timestamp': end_time.isoformat(),
|
||
'positive_cases': {
|
||
'count': len(positive_cases),
|
||
'results': positive_results
|
||
},
|
||
'negative_cases': {
|
||
'count': len(negative_cases),
|
||
'results': negative_results
|
||
},
|
||
'evaluation_mode': 'parallel' if enable_parallel else 'sequential',
|
||
'evaluation_duration_seconds': duration,
|
||
'metrics_used': list(evaluator.metrics.keys()),
|
||
'metrics_disabled': list(disabled_set) if disabled_set else [],
|
||
'metrics_enabled': list(enabled_set) if enabled_set else []
|
||
}
|
||
|
||
# 保存结果
|
||
print("=" * 80)
|
||
print("保存评估结果")
|
||
print("=" * 80)
|
||
|
||
full_result = {
|
||
'metadata': {
|
||
'version': '1.0',
|
||
'evaluation_date': end_time.isoformat(),
|
||
'test_set': test_set_path,
|
||
'systems': [system],
|
||
'evaluation_mode': 'parallel' if enable_parallel else 'sequential',
|
||
'metrics_used': list(evaluator.metrics.keys()),
|
||
'metrics_disabled': list(disabled_set) if disabled_set else []
|
||
},
|
||
'results': {
|
||
system: result
|
||
}
|
||
}
|
||
|
||
# 生成报告
|
||
reporter = JSONReporter()
|
||
|
||
# 构建文件名
|
||
mode_suffix = 'parallel' if enable_parallel else 'sequential'
|
||
metrics_suffix = '_'.join(sorted(evaluator.metrics.keys()))
|
||
output_path = f'data/results/{system}_{mode_suffix}_{metrics_suffix}_{end_time.strftime("%Y%m%d_%H%M%S")}.json'
|
||
|
||
reporter.generate_report(all_results=full_result, output_path=output_path)
|
||
|
||
print()
|
||
print("✅ 所有任务完成!")
|
||
print()
|
||
print(f"结果文件: {output_path}")
|
||
if logger:
|
||
print(f"日志文件: {logger.get_log_file_path()}")
|
||
print()
|
||
|
||
return 0
|
||
|
||
except Exception as e:
|
||
print()
|
||
print("=" * 80)
|
||
print("❌ 评估失败")
|
||
print("=" * 80)
|
||
print(f"错误类型: {type(e).__name__}")
|
||
print(f"错误信息: {e}")
|
||
print()
|
||
import traceback
|
||
traceback.print_exc()
|
||
return 1
|
||
|
||
|
||
def main():
|
||
"""主函数"""
|
||
parser = argparse.ArgumentParser(
|
||
description='可配置系统评估(支持启用/禁用特定指标)',
|
||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||
epilog="""
|
||
示例:
|
||
# 禁用最慢的指标 answer_correctness(推荐)
|
||
python scripts/evaluate_with_config.py --system zht-excel --disable answer_correctness
|
||
|
||
# 启用滚动更新(每完成一个问题就保存结果)
|
||
python scripts/evaluate_with_config.py --system zht-excel --disable answer_correctness --output data/results/rolling_update
|
||
|
||
# 只启用快速指标
|
||
python scripts/evaluate_with_config.py --system zht-excel --enable context_precision context_recall faithfulness
|
||
|
||
# 禁用多个指标
|
||
python scripts/evaluate_with_config.py --system zht-excel --disable answer_correctness faithfulness
|
||
|
||
# 组合使用:禁用慢速指标 + 禁用并行 + 禁用日志 + 滚动更新
|
||
python scripts/evaluate_with_config.py --system zht-excel --disable answer_correctness --no-parallel --no-logging --output data/results/test
|
||
|
||
可用指标:
|
||
- context_precision: 上下文精确度(快速,~15秒)
|
||
- context_recall: 上下文召回率(中等,~62秒)
|
||
- faithfulness: 忠实度(中等,~89秒)
|
||
- answer_relevance: 答案相关性(快速,~24秒)
|
||
- answer_correctness: 答案正确性(最慢,~307秒,占62%时间)
|
||
|
||
推荐配置:
|
||
- 快速测试: --disable answer_correctness
|
||
- 质量优先: --enable context_precision faithfulness answer_relevance
|
||
- 完整评估: (不使用 --disable 或 --enable)
|
||
- 滚动更新: --output <path> (每完成一个问题就更新结果文件)
|
||
"""
|
||
)
|
||
|
||
parser.add_argument(
|
||
'--system',
|
||
type=str,
|
||
required=True,
|
||
help='系统名称(如: coze-excel, kbs-text, zht-excel, zhtv2-text)'
|
||
)
|
||
|
||
parser.add_argument(
|
||
'--test-set',
|
||
type=str,
|
||
default='data/test_sets/ragas_test_cases_v3.1.json',
|
||
help='测试集路径(默认: data/test_sets/ragas_test_cases_v3.1.json)'
|
||
)
|
||
|
||
parser.add_argument(
|
||
'--disable',
|
||
nargs='+',
|
||
dest='disabled_metrics',
|
||
choices=['context_precision', 'context_recall', 'faithfulness', 'answer_relevance', 'answer_correctness'],
|
||
help='要禁用的指标列表'
|
||
)
|
||
|
||
parser.add_argument(
|
||
'--enable',
|
||
nargs='+',
|
||
dest='enabled_metrics',
|
||
choices=['context_precision', 'context_recall', 'faithfulness', 'answer_relevance', 'answer_correctness'],
|
||
help='要启用的指标列表(如果指定,只评估这些指标)'
|
||
)
|
||
|
||
parser.add_argument(
|
||
'--no-parallel',
|
||
action='store_true',
|
||
help='禁用并行评估(使用串行模式)'
|
||
)
|
||
|
||
parser.add_argument(
|
||
'--no-logging',
|
||
action='store_true',
|
||
help='禁用详细日志记录(默认启用)'
|
||
)
|
||
|
||
parser.add_argument(
|
||
'--output',
|
||
type=str,
|
||
dest='output_file',
|
||
help='输出文件路径(将实现滚动更新:每完成一个问题就更新文件)'
|
||
)
|
||
|
||
args = parser.parse_args()
|
||
|
||
# 检查是否同时指定了 --enable 和 --disable
|
||
if args.enabled_metrics and args.disabled_metrics:
|
||
print("⚠️ 警告: 同时指定了 --enable 和 --disable,将优先使用 --enable")
|
||
|
||
# 显示配置
|
||
print()
|
||
print("=" * 80)
|
||
print("评估配置")
|
||
print("=" * 80)
|
||
print(f"系统: {args.system}")
|
||
print(f"并行: {'启用' if not args.no_parallel else '禁用'}")
|
||
print(f"日志: {'启用' if not args.no_logging else '禁用'}")
|
||
print(f"滚动更新: {'启用' if args.output_file else '禁用'}")
|
||
|
||
if args.enabled_metrics:
|
||
print(f"启用的指标: {', '.join(args.enabled_metrics)}")
|
||
elif args.disabled_metrics:
|
||
print(f"禁用的指标: {', '.join(args.disabled_metrics)}")
|
||
else:
|
||
print("指标: 全部启用(默认)")
|
||
|
||
if args.output_file:
|
||
print(f"输出文件: {args.output_file}")
|
||
print(f" - 正向用例: {Path(args.output_file).parent / Path(args.output_file).stem}_positive.json")
|
||
print(f" - 负向用例: {Path(args.output_file).parent / Path(args.output_file).stem}_negative.json")
|
||
|
||
print("=" * 80)
|
||
|
||
# 运行评估
|
||
exit_code = asyncio.run(evaluate_system(
|
||
system=args.system,
|
||
test_set_path=args.test_set,
|
||
enable_parallel=not args.no_parallel,
|
||
enable_logging=not args.no_logging,
|
||
disabled_metrics=args.disabled_metrics,
|
||
enabled_metrics=args.enabled_metrics,
|
||
output_file=args.output_file
|
||
))
|
||
|
||
return exit_code
|
||
|
||
|
||
if __name__ == '__main__':
|
||
try:
|
||
exit_code = main()
|
||
sys.exit(exit_code)
|
||
except KeyboardInterrupt:
|
||
print("\n\n⚠️ 评估被用户中断")
|
||
sys.exit(1)
|
||
except Exception as e:
|
||
print(f"\n\n❌ 未预期的错误: {e}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
sys.exit(1)
|