235 lines
6.7 KiB
Python
235 lines
6.7 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
|
|||
|
|
):
|
|||
|
|
"""
|
|||
|
|
评估单个系统
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
system: 系统名称
|
|||
|
|
test_set_path: 测试集路径
|
|||
|
|
enable_parallel: 是否启用并行评估
|
|||
|
|
enable_logging: 是否启用详细日志
|
|||
|
|
"""
|
|||
|
|
from src.transformers.data_converter import DataConverter
|
|||
|
|
from src.evaluators.parallel_ragas_evaluator import ParallelRAGAsEvaluator
|
|||
|
|
from src.utils.evaluation_logger import EvaluationLogger
|
|||
|
|
from src.reporters.json_reporter import JSONReporter
|
|||
|
|
|
|||
|
|
print()
|
|||
|
|
print("=" * 80)
|
|||
|
|
print(f"评估系统: {system.upper()}")
|
|||
|
|
print(f"并行模式: {'启用' if enable_parallel else '禁用'}")
|
|||
|
|
print(f"日志记录: {'启用' if enable_logging else '禁用'}")
|
|||
|
|
print("=" * 80)
|
|||
|
|
print()
|
|||
|
|
|
|||
|
|
# 创建日志记录器
|
|||
|
|
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()
|
|||
|
|
|
|||
|
|
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()
|
|||
|
|
|
|||
|
|
# 创建并行评估器
|
|||
|
|
evaluator = ParallelRAGAsEvaluator(
|
|||
|
|
logger=logger,
|
|||
|
|
enable_parallel=enable_parallel
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
# 评估正向用例
|
|||
|
|
print(f"[2/3] 评估正向用例...")
|
|||
|
|
positive_results = await evaluator.evaluate_batch(positive_cases)
|
|||
|
|
print()
|
|||
|
|
|
|||
|
|
# 评估负向用例
|
|||
|
|
print(f"[3/3] 评估负向用例...")
|
|||
|
|
negative_results = await evaluator.evaluate_batch(negative_cases)
|
|||
|
|
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
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
# 保存结果
|
|||
|
|
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'
|
|||
|
|
},
|
|||
|
|
'results': {
|
|||
|
|
system: result
|
|||
|
|
}
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
# 生成报告
|
|||
|
|
reporter = JSONReporter()
|
|||
|
|
mode_suffix = 'parallel' if enable_parallel else 'sequential'
|
|||
|
|
output_path = f'data/results/{system}_{mode_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="""
|
|||
|
|
示例:
|
|||
|
|
# 使用并行模式评估(推荐)
|
|||
|
|
python scripts/evaluate_single_system_parallel.py --system zht-excel
|
|||
|
|
|
|||
|
|
# 使用串行模式评估(对比)
|
|||
|
|
python scripts/evaluate_single_system_parallel.py --system zht-excel --no-parallel
|
|||
|
|
|
|||
|
|
# 禁用日志
|
|||
|
|
python scripts/evaluate_single_system_parallel.py --system zht-excel --no-logging
|
|||
|
|
"""
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
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(
|
|||
|
|
'--no-parallel',
|
|||
|
|
action='store_true',
|
|||
|
|
help='禁用并行评估(使用串行模式)'
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
parser.add_argument(
|
|||
|
|
'--no-logging',
|
|||
|
|
action='store_true',
|
|||
|
|
help='禁用详细日志记录(默认启用)'
|
|||
|
|
)
|
|||
|
|
|
|||
|
|
args = parser.parse_args()
|
|||
|
|
|
|||
|
|
# 运行评估
|
|||
|
|
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
|
|||
|
|
))
|
|||
|
|
|
|||
|
|
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)
|