feat: 实现实时进度跟踪和滚动更新功能
新增功能: - ✅ 实时进度跟踪:进度条、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>
This commit is contained in:
1 parent
eb0897a31b
commit
cd1ab744c7
6 files changed
+913
-27
No files matched your search
@@ -0,0 +1,296 @@
|
||||
"""
|
||||
评估进度跟踪器:实时显示评估进度、状态和时间预估
|
||||
"""
|
||||
import time
|
||||
import sys
|
||||
from typing import Optional, List, Dict
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
|
||||
class ProgressTracker:
|
||||
"""评估进度跟踪器"""
|
||||
|
||||
def __init__(self, total_questions: int, total_metrics: int = 5):
|
||||
"""
|
||||
初始化进度跟踪器
|
||||
|
||||
Args:
|
||||
total_questions: 总问题数
|
||||
total_metrics: 总指标数(默认5个)
|
||||
"""
|
||||
self.total_questions = total_questions
|
||||
self.total_metrics = total_metrics
|
||||
self.total_tasks = total_questions * total_metrics
|
||||
|
||||
self.current_question = 0
|
||||
self.current_metric = 0
|
||||
self.completed_tasks = 0
|
||||
|
||||
self.start_time = time.time()
|
||||
self.question_start_time = None
|
||||
self.metric_start_times = {}
|
||||
|
||||
# 存储每个指标的历史耗时(用于预估)
|
||||
self.metric_durations = {
|
||||
'context_precision': [],
|
||||
'context_recall': [],
|
||||
'faithfulness': [],
|
||||
'answer_relevance': [],
|
||||
'answer_correctness': []
|
||||
}
|
||||
|
||||
def get_progress_bar(self, width: int = 40) -> str:
|
||||
"""
|
||||
获取进度条
|
||||
|
||||
Args:
|
||||
width: 进度条宽度
|
||||
|
||||
Returns:
|
||||
进度条字符串
|
||||
"""
|
||||
if self.total_tasks == 0:
|
||||
return "[" + "=" * width + "]"
|
||||
|
||||
progress = self.completed_tasks / self.total_tasks
|
||||
filled = int(width * progress)
|
||||
bar = "█" * filled + "░" * (width - filled)
|
||||
percentage = progress * 100
|
||||
|
||||
return f"[{bar}] {percentage:.1f}%"
|
||||
|
||||
def get_eta(self) -> str:
|
||||
"""
|
||||
获取预估完成时间
|
||||
|
||||
Returns:
|
||||
ETA字符串
|
||||
"""
|
||||
if self.completed_tasks == 0:
|
||||
return "计算中..."
|
||||
|
||||
elapsed = time.time() - self.start_time
|
||||
avg_time_per_task = elapsed / self.completed_tasks
|
||||
remaining_tasks = self.total_tasks - self.completed_tasks
|
||||
eta_seconds = remaining_tasks * avg_time_per_task
|
||||
|
||||
if eta_seconds < 60:
|
||||
return f"约 {int(eta_seconds)} 秒"
|
||||
elif eta_seconds < 3600:
|
||||
minutes = int(eta_seconds / 60)
|
||||
seconds = int(eta_seconds % 60)
|
||||
return f"约 {minutes} 分 {seconds} 秒"
|
||||
else:
|
||||
hours = int(eta_seconds / 3600)
|
||||
minutes = int((eta_seconds % 3600) / 60)
|
||||
return f"约 {hours} 小时 {minutes} 分"
|
||||
|
||||
def get_elapsed_time(self) -> str:
|
||||
"""
|
||||
获取已用时间
|
||||
|
||||
Returns:
|
||||
已用时间字符串
|
||||
"""
|
||||
elapsed = time.time() - self.start_time
|
||||
|
||||
if elapsed < 60:
|
||||
return f"{int(elapsed)} 秒"
|
||||
elif elapsed < 3600:
|
||||
minutes = int(elapsed / 60)
|
||||
seconds = int(elapsed % 60)
|
||||
return f"{minutes} 分 {seconds} 秒"
|
||||
else:
|
||||
hours = int(elapsed / 3600)
|
||||
minutes = int((elapsed % 3600) / 60)
|
||||
return f"{hours} 小时 {minutes} 分"
|
||||
|
||||
def start_question(self, question_id: str, question: str = ""):
|
||||
"""
|
||||
开始评估一个问题
|
||||
|
||||
Args:
|
||||
question_id: 问题ID
|
||||
question: 问题内容
|
||||
"""
|
||||
self.current_question += 1
|
||||
self.question_start_time = time.time()
|
||||
|
||||
print()
|
||||
print("=" * 80)
|
||||
print(f"📝 问题 [{self.current_question}/{self.total_questions}]: {question_id}")
|
||||
if question:
|
||||
print(f"问题内容: {question}")
|
||||
print(f"进度: {self.get_progress_bar()}")
|
||||
print(f"已用: {self.get_elapsed_time()} | 预估剩余: {self.get_eta()}")
|
||||
print("=" * 80)
|
||||
print()
|
||||
|
||||
def start_metric(self, metric_name: str):
|
||||
"""
|
||||
开始评估一个指标
|
||||
|
||||
Args:
|
||||
metric_name: 指标名称
|
||||
"""
|
||||
self.current_metric += 1
|
||||
self.metric_start_times[metric_name] = time.time()
|
||||
|
||||
metric_display = self._get_metric_display_name(metric_name)
|
||||
print(f" ⏳ [{self.current_metric}/{self.total_metrics}] {metric_display} ... ", end="", flush=True)
|
||||
|
||||
def complete_metric(self, metric_name: str, score: float, success: bool = True):
|
||||
"""
|
||||
完成一个指标评估
|
||||
|
||||
Args:
|
||||
metric_name: 指标名称
|
||||
score: 得分
|
||||
success: 是否成功
|
||||
"""
|
||||
duration = time.time() - self.metric_start_times.get(metric_name, time.time())
|
||||
self.metric_durations[metric_name].append(duration)
|
||||
self.completed_tasks += 1
|
||||
|
||||
metric_display = self._get_metric_display_name(metric_name)
|
||||
|
||||
if success:
|
||||
status = "✅" if score > 0.7 else "⚠️" if score > 0.5 else "❌"
|
||||
print(f"{status} {score:.4f} ({duration:.1f}秒)")
|
||||
else:
|
||||
print(f"❌ 失败 ({duration:.1f}秒)")
|
||||
|
||||
# 更新进度
|
||||
if self.current_metric >= self.total_metrics:
|
||||
print()
|
||||
print(f" ✅ 问题 {self.current_question}/{self.total_questions} 完成!")
|
||||
print(f" 总耗时: {time.time() - self.question_start_time:.1f} 秒")
|
||||
self.current_metric = 0
|
||||
|
||||
def complete_question(self):
|
||||
"""完成一个问题评估"""
|
||||
self.question_start_time = None
|
||||
|
||||
def complete_session(self):
|
||||
"""完成整个评估会话"""
|
||||
total_time = time.time() - self.start_time
|
||||
print()
|
||||
print("=" * 80)
|
||||
print("✅ 所有评估完成!")
|
||||
print("=" * 80)
|
||||
print(f"总用时: {self._format_duration(total_time)}")
|
||||
print(f"总问题: {self.total_questions}")
|
||||
print(f"总指标: {self.total_metrics}")
|
||||
print(f"平均每问题: {total_time / self.total_questions:.1f} 秒")
|
||||
print()
|
||||
|
||||
# 显示各指标平均耗时
|
||||
print("📊 各指标平均耗时:")
|
||||
for metric_name, durations in self.metric_durations.items():
|
||||
if durations:
|
||||
avg_duration = sum(durations) / len(durations)
|
||||
count = len(durations)
|
||||
metric_display = self._get_metric_display_name(metric_name, short=True)
|
||||
print(f" - {metric_display:20s}: {avg_duration:6.1f} 秒/次 ({count} 次)")
|
||||
print()
|
||||
|
||||
def _get_metric_display_name(self, metric_name: str, short: bool = False) -> str:
|
||||
"""
|
||||
获取指标的显示名称
|
||||
|
||||
Args:
|
||||
metric_name: 指标名称
|
||||
short: 是否使用短名称
|
||||
|
||||
Returns:
|
||||
显示名称
|
||||
"""
|
||||
display_names = {
|
||||
'context_precision': '上下文精确度',
|
||||
'context_recall': '上下文召回率',
|
||||
'faithfulness': '忠实度',
|
||||
'answer_relevance': '答案相关性',
|
||||
'answer_correctness': '答案正确性'
|
||||
}
|
||||
|
||||
short_names = {
|
||||
'context_precision': '精确度',
|
||||
'context_recall': '召回率',
|
||||
'faithfulness': '忠实度',
|
||||
'answer_relevance': '相关性',
|
||||
'answer_correctness': '正确性'
|
||||
}
|
||||
|
||||
if short:
|
||||
return short_names.get(metric_name, metric_name)
|
||||
else:
|
||||
return display_names.get(metric_name, metric_name)
|
||||
|
||||
def _format_duration(self, seconds: float) -> str:
|
||||
"""
|
||||
格式化时间长度
|
||||
|
||||
Args:
|
||||
seconds: 秒数
|
||||
|
||||
Returns:
|
||||
格式化的时间字符串
|
||||
"""
|
||||
if seconds < 60:
|
||||
return f"{int(seconds)} 秒"
|
||||
elif seconds < 3600:
|
||||
minutes = int(seconds / 60)
|
||||
secs = int(seconds % 60)
|
||||
return f"{minutes} 分 {secs} 秒"
|
||||
else:
|
||||
hours = int(seconds / 3600)
|
||||
minutes = int((seconds % 3600) / 60)
|
||||
return f"{hours} 小时 {minutes} 分"
|
||||
|
||||
def print_summary(self, results: Dict):
|
||||
"""
|
||||
打印评估摘要
|
||||
|
||||
Args:
|
||||
results: 评估结果字典
|
||||
"""
|
||||
print()
|
||||
print("=" * 80)
|
||||
print("📈 评估结果摘要")
|
||||
print("=" * 80)
|
||||
print()
|
||||
|
||||
# 统计指标得分
|
||||
all_scores = {}
|
||||
for result in results:
|
||||
scores = result.get('scores', {})
|
||||
for metric_name, score in scores.items():
|
||||
if score is not None:
|
||||
if metric_name not in all_scores:
|
||||
all_scores[metric_name] = []
|
||||
all_scores[metric_name].append(score)
|
||||
|
||||
# 显示各指标统计
|
||||
if all_scores:
|
||||
print("各指标得分统计:")
|
||||
print()
|
||||
for metric_name in ['context_precision', 'context_recall', 'faithfulness',
|
||||
'answer_relevance', 'answer_correctness']:
|
||||
if metric_name in all_scores:
|
||||
scores = all_scores[metric_name]
|
||||
avg_score = sum(scores) / len(scores)
|
||||
min_score = min(scores)
|
||||
max_score = max(scores)
|
||||
metric_display = self._get_metric_display_name(metric_name, short=True)
|
||||
|
||||
print(f" {metric_display:10s}: 平均 {avg_score:.4f} | 最小 {min_score:.4f} | 最大 {max_score:.4f} | 样本 {len(scores)} 个")
|
||||
print()
|
||||
|
||||
def print_error(self, error_msg: str):
|
||||
"""
|
||||
打印错误信息
|
||||
|
||||
Args:
|
||||
error_msg: 错误消息
|
||||
"""
|
||||
print(f" ❌ 错误: {error_msg}", file=sys.stderr)
|
||||
Reference in new issue
Block a user