274 lines
7.9 KiB
Python
274 lines
7.9 KiB
Python
"""
|
|||
|
|
Phase 3 功能演示: 报告可视化和历史趋势分析
|
||
|
|
|
||
|
|
本示例展示如何使用:
|
||
|
|
1. 报告可视化 (HTML报告和图表)
|
||
|
|
2. 历史数据存储
|
||
|
|
3. 趋势分析
|
||
|
|
4. 性能回归检测
|
||
|
|
"""
|
||
|
|
|
||
|
|
import sys
|
||
|
|
import os
|
||
|
|
sys.path.insert(0, os.path.dirname(__file__))
|
||
|
|
|
||
|
|
from datetime import datetime, timedelta
|
||
|
|
from report.aggregator import ResultAggregator, EvaluationSummary, MetricStats
|
||
|
|
from report.generator import ReportGenerator
|
||
|
|
from report.visualizer import ReportVisualizer
|
||
|
|
|
||
|
|
|
||
|
|
def demo_visualization():
|
||
|
|
"""演示报告可视化功能"""
|
||
|
|
print("=" * 60)
|
||
|
|
print("演示 1: 报告可视化")
|
||
|
|
print("=" * 60)
|
||
|
|
|
||
|
|
# 创建测试数据
|
||
|
|
summary = EvaluationSummary(
|
||
|
|
evaluation_id="eval-demo-001",
|
||
|
|
knowledge_base_id="kb-demo",
|
||
|
|
testset_id="ts-demo",
|
||
|
|
total_questions=20,
|
||
|
|
successful_questions=18,
|
||
|
|
failed_questions=2,
|
||
|
|
overall_score=82.5,
|
||
|
|
metric_stats={
|
||
|
|
'context_recall': MetricStats(
|
||
|
|
name='context_recall',
|
||
|
|
mean=0.85,
|
||
|
|
median=0.87,
|
||
|
|
std_dev=0.12,
|
||
|
|
min=0.60,
|
||
|
|
max=0.98,
|
||
|
|
count=18,
|
||
|
|
pass_rate=0.83
|
||
|
|
),
|
||
|
|
'context_precision': MetricStats(
|
||
|
|
name='context_precision',
|
||
|
|
mean=0.82,
|
||
|
|
median=0.84,
|
||
|
|
std_dev=0.10,
|
||
|
|
min=0.65,
|
||
|
|
max=0.95,
|
||
|
|
count=18,
|
||
|
|
pass_rate=0.78
|
||
|
|
),
|
||
|
|
'faithfulness': MetricStats(
|
||
|
|
name='faithfulness',
|
||
|
|
mean=0.88,
|
||
|
|
median=0.90,
|
||
|
|
std_dev=0.08,
|
||
|
|
min=0.70,
|
||
|
|
max=0.98,
|
||
|
|
count=18,
|
||
|
|
pass_rate=0.89
|
||
|
|
),
|
||
|
|
'answer_relevancy': MetricStats(
|
||
|
|
name='answer_relevancy',
|
||
|
|
mean=0.80,
|
||
|
|
median=0.82,
|
||
|
|
std_dev=0.11,
|
||
|
|
min=0.60,
|
||
|
|
max=0.95,
|
||
|
|
count=18,
|
||
|
|
pass_rate=0.72
|
||
|
|
)
|
||
|
|
},
|
||
|
|
avg_retrieval_time_ms=180.5,
|
||
|
|
avg_generation_time_ms=850.3,
|
||
|
|
created_at=datetime.now()
|
||
|
|
)
|
||
|
|
|
||
|
|
# 创建测试结果
|
||
|
|
results = [
|
||
|
|
{
|
||
|
|
'question_index': i,
|
||
|
|
'question_text': f'测试问题 {i+1}',
|
||
|
|
'metrics': {
|
||
|
|
'context_recall': 0.85 + (i % 3) * 0.05,
|
||
|
|
'context_precision': 0.82 + (i % 3) * 0.04,
|
||
|
|
'faithfulness': 0.88 + (i % 3) * 0.03,
|
||
|
|
'answer_relevancy': 0.80 + (i % 3) * 0.05
|
||
|
|
},
|
||
|
|
'retrieval_time_ms': 180 + i * 5,
|
||
|
|
'generation_time_ms': 850 + i * 10,
|
||
|
|
'metadata': {'source': f'doc{i % 3 + 1}.pdf'}
|
||
|
|
}
|
||
|
|
for i in range(18)
|
||
|
|
] + [
|
||
|
|
{
|
||
|
|
'question_index': 18,
|
||
|
|
'question_text': '失败问题 1',
|
||
|
|
'metrics': None,
|
||
|
|
'error': 'Evaluation timeout'
|
||
|
|
},
|
||
|
|
{
|
||
|
|
'question_index': 19,
|
||
|
|
'question_text': '失败问题 2',
|
||
|
|
'metrics': {
|
||
|
|
'context_recall': 0.3,
|
||
|
|
'context_precision': 0.35,
|
||
|
|
'faithfulness': 0.4,
|
||
|
|
'answer_relevancy': 0.38
|
||
|
|
},
|
||
|
|
'retrieval_time_ms': 250,
|
||
|
|
'generation_time_ms': 1200
|
||
|
|
}
|
||
|
|
]
|
||
|
|
|
||
|
|
# 生成HTML报告
|
||
|
|
try:
|
||
|
|
visualizer = ReportVisualizer()
|
||
|
|
output_path = 'demo_report.html'
|
||
|
|
|
||
|
|
visualizer.generate_html_report(
|
||
|
|
summary,
|
||
|
|
results,
|
||
|
|
output_path,
|
||
|
|
include_charts=True
|
||
|
|
)
|
||
|
|
|
||
|
|
print(f"[OK] HTML报告已生成: {output_path}")
|
||
|
|
print(f" - 包含雷达图、柱状图、饼图")
|
||
|
|
print(f" - 整体评分: {summary.overall_score}")
|
||
|
|
print(f" - 成功率: {summary.successful_questions}/{summary.total_questions}")
|
||
|
|
|
||
|
|
except ImportError as e:
|
||
|
|
print(f"[ERROR] 无法生成可视化报告: {e}")
|
||
|
|
print(" 请安装 plotly: pip install plotly>=5.18.0")
|
||
|
|
|
||
|
|
print()
|
||
|
|
|
||
|
|
|
||
|
|
def demo_history_and_trend():
|
||
|
|
"""演示历史数据和趋势分析功能"""
|
||
|
|
print("=" * 60)
|
||
|
|
print("演示 2: 历史数据存储和趋势分析")
|
||
|
|
print("=" * 60)
|
||
|
|
|
||
|
|
# 注意: 这个演示需要数据库连接
|
||
|
|
# 实际使用时需要配置数据库
|
||
|
|
print("历史数据存储功能:")
|
||
|
|
print(" - HistoryManager.save_evaluation_history() - 保存评估历史")
|
||
|
|
print(" - HistoryManager.get_history_by_knowledge_base() - 获取知识库历史")
|
||
|
|
print(" - HistoryManager.get_metric_trend() - 获取指标趋势")
|
||
|
|
print()
|
||
|
|
|
||
|
|
print("趋势分析功能:")
|
||
|
|
print(" - TrendAnalyzer.compare_with_baseline() - 与基线对比")
|
||
|
|
print(" - TrendAnalyzer.analyze_trend() - 分析指标趋势")
|
||
|
|
print(" - TrendAnalyzer.detect_regression() - 检测性能回归")
|
||
|
|
print(" - TrendAnalyzer.generate_trend_summary() - 生成趋势摘要")
|
||
|
|
print()
|
||
|
|
|
||
|
|
# 模拟趋势数据
|
||
|
|
print("模拟趋势分析结果:")
|
||
|
|
print()
|
||
|
|
|
||
|
|
# 模拟对比结果
|
||
|
|
print("与基线对比:")
|
||
|
|
comparison = {
|
||
|
|
'context_recall': {
|
||
|
|
'current': 0.85,
|
||
|
|
'baseline': 0.80,
|
||
|
|
'change': 0.05,
|
||
|
|
'change_pct': 6.25,
|
||
|
|
'status': 'improved'
|
||
|
|
},
|
||
|
|
'faithfulness': {
|
||
|
|
'current': 0.88,
|
||
|
|
'baseline': 0.90,
|
||
|
|
'change': -0.02,
|
||
|
|
'change_pct': -2.22,
|
||
|
|
'status': 'stable'
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
for metric, comp in comparison.items():
|
||
|
|
status_icon = "UP" if comp['status'] == 'improved' else "STABLE" if comp['status'] == 'stable' else "DOWN"
|
||
|
|
print(f" {status_icon} {metric}: {comp['current']:.3f} (基线: {comp['baseline']:.3f}, "
|
||
|
|
f"变化: {comp['change_pct']:+.1f}%)")
|
||
|
|
|
||
|
|
print()
|
||
|
|
|
||
|
|
# 模拟回归检测
|
||
|
|
print("性能回归检测:")
|
||
|
|
print(" [OK] 未检测到显著回归 (阈值: 5%)")
|
||
|
|
print()
|
||
|
|
|
||
|
|
|
||
|
|
def demo_trend_visualization():
|
||
|
|
"""演示趋势可视化功能"""
|
||
|
|
print("=" * 60)
|
||
|
|
print("演示 3: 趋势可视化")
|
||
|
|
print("=" * 60)
|
||
|
|
|
||
|
|
# 创建模拟历史数据
|
||
|
|
history_data = []
|
||
|
|
base_date = datetime.now() - timedelta(days=30)
|
||
|
|
|
||
|
|
for i in range(10):
|
||
|
|
date = base_date + timedelta(days=i * 3)
|
||
|
|
history_data.append({
|
||
|
|
'timestamp': date.strftime('%Y-%m-%d'),
|
||
|
|
'metrics': {
|
||
|
|
'context_recall': 0.70 + i * 0.015, # 逐渐改进
|
||
|
|
'faithfulness': 0.85 - i * 0.005, # 轻微下降
|
||
|
|
'answer_relevancy': 0.75 + (i % 3) * 0.02 # 波动
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
# 生成趋势图
|
||
|
|
try:
|
||
|
|
visualizer = ReportVisualizer()
|
||
|
|
output_path = 'demo_trend.html'
|
||
|
|
|
||
|
|
visualizer.create_trend_chart(history_data, output_path)
|
||
|
|
|
||
|
|
print(f"[OK] 趋势图已生成: {output_path}")
|
||
|
|
print(f" - 包含 {len(history_data)} 个数据点")
|
||
|
|
print(f" - 时间跨度: 30天")
|
||
|
|
print(f" - 指标数量: 3个")
|
||
|
|
|
||
|
|
except ImportError as e:
|
||
|
|
print(f"[ERROR] 无法生成趋势图: {e}")
|
||
|
|
print(" 请安装 plotly: pip install plotly>=5.18.0")
|
||
|
|
|
||
|
|
print()
|
||
|
|
|
||
|
|
|
||
|
|
def main():
|
||
|
|
"""主函数"""
|
||
|
|
print()
|
||
|
|
print("=" + "=" * 58 + "=")
|
||
|
|
print("|" + " " * 10 + "RAG评估框架 - Phase 3 功能演示" + " " * 16 + "|")
|
||
|
|
print("=" + "=" * 58 + "=")
|
||
|
|
print()
|
||
|
|
|
||
|
|
# 演示1: 报告可视化
|
||
|
|
demo_visualization()
|
||
|
|
|
||
|
|
# 演示2: 历史数据和趋势分析
|
||
|
|
demo_history_and_trend()
|
||
|
|
|
||
|
|
# 演示3: 趋势可视化
|
||
|
|
demo_trend_visualization()
|
||
|
|
|
||
|
|
print("=" * 60)
|
||
|
|
print("演示完成!")
|
||
|
|
print("=" * 60)
|
||
|
|
print()
|
||
|
|
print("Phase 3 已完成的功能:")
|
||
|
|
print(" [OK] 报告可视化 (HTML报告、图表)")
|
||
|
|
print(" [OK] 评估历史数据存储")
|
||
|
|
print(" [OK] 趋势对比分析")
|
||
|
|
print(" [OK] 性能回归检测")
|
||
|
|
print(" [OK] 单元测试覆盖")
|
||
|
|
print()
|
||
|
|
print("下一步: Phase 4 - API和用户界面")
|
||
|
|
print()
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == '__main__':
|
||
|
|
main()
|