#!/usr/bin/env python # -*- coding: utf-8 -*- """ 单系统评估测试 - 验证结果保存功能 测试流程: 1. 构造单个验证数据 2. 运行单系统评估 3. 验证结果文件是否正确保存 """ import sys import os import json import shutil 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__)))) def create_test_data(): """创建测试数据文件""" print("=" * 80) print("步骤 1: 创建测试数据") print("=" * 80) # 构造单个测试数据 test_data = [{ "question_id": "q001", "question": "签约流程是什么?", "test_type": "简单检索", "category": "positive", "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "logid": "test_log_id_001", "performance": { "total_time_ms": 5000, "first_response_time_ms": 2000, "knowledge_retrieval_time_ms": 1500, "total_tokens": 1000 }, "answer": "PC端签约流程:在还款申请里面→选择到期还款→选择变更还款计划→提交就可以了。", "knowledge_retrieval": { "dataset_id": "test_dataset", "query": "签约流程是什么?", "parameters": { "top_k": 10, "min_score": 0.5 }, "retrieved_slices": [ { "index": 0, "score": 0.95, "content": "{\"分类\":\"产品知识\",\"答案\":\"PC端签约流程:在还款申请里面→选择到期还款→选择变更还款计划→提交就可以了\",\"问题\":\"签约流程\"}", "meta": { "document": {"id": "test_doc_001"}, "slice_id": "test_slice_001" } } ] } }] # 保存测试数据文件(使用 -excel 后缀以匹配系统名) test_data_path = Path("data/test_sets/test-single-excel-raw-data.json") test_data_path.parent.mkdir(parents=True, exist_ok=True) with open(test_data_path, 'w', encoding='utf-8') as f: json.dump(test_data, f, ensure_ascii=False, indent=2) print(f"✅ 测试数据已创建: {test_data_path}") print(f" 数据条目数: {len(test_data)}") print(f" 问题ID: {test_data[0]['question_id']}") print(f" 问题: {test_data[0]['question']}") print() return test_data_path def run_evaluation(system_name: str): """运行单系统评估""" import asyncio from src.evaluators.batch_evaluator import BatchEvaluator from src.reporters.json_reporter import JSONReporter print("=" * 80) print("步骤 2: 运行单系统评估") print("=" * 80) # 测试集路径 test_set_path = "data/test_sets/ragas_test_cases_v3.1.json" print(f"系统名称: {system_name}") print(f"测试集路径: {test_set_path}") print(f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print() # 创建批评估器 evaluator = BatchEvaluator( systems=[system_name], test_set_path=test_set_path, enable_logging=True ) # 运行评估(异步) print("正在运行评估...") result = asyncio.run(evaluator.evaluate_single_system(system_name)) print() print("✅ 评估完成") print(f" 结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print() # 保存结果到文件 print("=" * 80) print("保存评估结果") print("=" * 80) # 创建完整的结果结构 full_result = { 'metadata': { 'version': '1.0', 'evaluation_date': datetime.now().isoformat(), 'test_set': test_set_path, 'systems': [system_name] }, 'results': { system_name: result } } # 使用 JSONReporter 保存结果 reporter = JSONReporter() output_path = f'data/results/{system_name}_test_{datetime.now().strftime("%Y%m%d_%H%M%S")}.json' reporter.generate_report(all_results=full_result, output_path=output_path) print(f"✅ 结果已保存到: {output_path}") print() return full_result def verify_output_files(system_name: str): """验证输出文件""" print("=" * 80) print("步骤 3: 验证输出文件") print("=" * 80) # 定义要检查的文件 results_dir = Path("data/results") logs_dir = Path("logs") files_to_check = [] # 查找结果文件 if results_dir.exists(): result_files = list(results_dir.glob(f"{system_name}_*.json")) files_to_check.extend(result_files) # 查找日志文件 if logs_dir.exists(): log_files = list(logs_dir.glob(f"{system_name}_*.log")) files_to_check.extend(log_files) if not files_to_check: print("❌ 未找到任何输出文件") return False print(f"找到 {len(files_to_check)} 个文件:") print() all_valid = True for file_path in sorted(files_to_check): exists = file_path.exists() size_kb = file_path.stat().st_size / 1024 if exists else 0 status = "✅" if exists and size_kb > 0 else "❌" print(f"{status} {file_path}") print(f" 大小: {size_kb:.2f} KB") # 如果是JSON文件,验证内容 if file_path.suffix == '.json' and exists and size_kb > 0: try: with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) print(f" 格式: JSON ✅") # 检查必要字段 if 'metadata' in data: print(f" metadata 字段: ✅") if 'results' in data: print(f" results 字段: ✅") if system_name in data['results']: print(f" {system_name} 结果: ✅") result = data['results'][system_name] if 'overall_score' in result: print(f" overall_score: {result['overall_score']:.4f}") if 'comparison' in data: print(f" comparison 字段: ✅") except json.JSONDecodeError as e: print(f" ❌ JSON 解析失败: {e}") all_valid = False except Exception as e: print(f" ❌ 验证失败: {e}") all_valid = False print() return all_valid def cleanup_test_data(): """清理测试数据""" print("=" * 80) print("步骤 4: 清理测试数据") print("=" * 80) test_data_path = Path("data/test_sets/test-single-excel-raw-data.json") if test_data_path.exists(): test_data_path.unlink() print(f"✅ 已删除测试数据: {test_data_path}") else: print(f"⚠️ 测试数据不存在: {test_data_path}") print() def main(): """主函数""" print() print("╔" + "=" * 78 + "╗") print("║" + " " * 20 + "单系统评估测试" + " " * 44 + "║") print("╚" + "=" * 78 + "╝") print() # 测试系统名称 test_system = "test-single-excel" try: # 步骤1: 创建测试数据 test_data_path = create_test_data() # 步骤2: 运行评估 result = run_evaluation(test_system) # 步骤3: 验证输出 success = verify_output_files(test_system) # 步骤4: 清理测试数据 cleanup_test_data() # 总结 print("=" * 80) print("测试总结") print("=" * 80) if success: print("✅ 所有测试通过!") print() print("评估结果已正确保存到文件:") print(f" - 结果文件: data/results/{test_system}_*.json") print(f" - 日志文件: logs/{test_system}_*.log") else: print("❌ 测试失败,请检查错误信息") return 1 print("=" * 80) 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 if __name__ == '__main__': exit_code = main() input("\n按 Enter 键退出...") sys.exit(exit_code)