Initial commit
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
commit
4ecf7b351d
143 files changed
+24156
No files matched your search
@@ -0,0 +1,675 @@
|
||||
"""
|
||||
Report visualization module for RAG evaluation
|
||||
"""
|
||||
|
||||
from typing import Dict, Any, List, Optional
|
||||
import json
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
try:
|
||||
import plotly.graph_objects as go
|
||||
from plotly.subplots import make_subplots
|
||||
PLOTLY_AVAILABLE = True
|
||||
except ImportError:
|
||||
PLOTLY_AVAILABLE = False
|
||||
|
||||
from .aggregator import EvaluationSummary
|
||||
|
||||
|
||||
class ReportVisualizer:
|
||||
"""报告可视化器"""
|
||||
|
||||
def __init__(self):
|
||||
"""初始化可视化器"""
|
||||
if not PLOTLY_AVAILABLE:
|
||||
raise ImportError(
|
||||
"Plotly is required for visualization. "
|
||||
"Install it with: pip install plotly"
|
||||
)
|
||||
|
||||
def generate_html_report(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]],
|
||||
output_path: str,
|
||||
include_charts: bool = True
|
||||
) -> None:
|
||||
"""
|
||||
生成HTML格式报告
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
results: 评估结果列表
|
||||
output_path: 输出路径
|
||||
include_charts: 是否包含图表
|
||||
"""
|
||||
html_content = self._generate_html_content(
|
||||
summary, results, include_charts
|
||||
)
|
||||
|
||||
with open(output_path, 'w', encoding='utf-8') as f:
|
||||
f.write(html_content)
|
||||
|
||||
def _generate_html_content(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]],
|
||||
include_charts: bool
|
||||
) -> str:
|
||||
"""
|
||||
生成HTML内容
|
||||
|
||||
Args:
|
||||
summary: 评估摘要
|
||||
results: 评估结果列表
|
||||
include_charts: 是否包含图表
|
||||
|
||||
Returns:
|
||||
HTML字符串
|
||||
"""
|
||||
# 生成图表
|
||||
charts_html = ""
|
||||
if include_charts:
|
||||
charts_html = self._generate_charts_html(summary, results)
|
||||
|
||||
# 生成完整HTML
|
||||
html = f"""
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>RAG评估报告 - {summary.evaluation_id}</title>
|
||||
<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
|
||||
<style>
|
||||
{self._get_css_styles()}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1>RAG评估报告</h1>
|
||||
<p class="subtitle">评估ID: {summary.evaluation_id}</p>
|
||||
<p class="timestamp">生成时间: {summary.created_at.strftime('%Y-%m-%d %H:%M:%S')}</p>
|
||||
</header>
|
||||
|
||||
{self._generate_executive_summary_html(summary)}
|
||||
{charts_html}
|
||||
{self._generate_metrics_table_html(summary)}
|
||||
{self._generate_failed_cases_html(results)}
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _get_css_styles(self) -> str:
|
||||
"""获取CSS样式"""
|
||||
return """
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
line-height: 1.6;
|
||||
color: #333;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
header {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
padding: 30px;
|
||||
border-radius: 10px;
|
||||
margin-bottom: 30px;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 2.5em;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
font-size: 1.1em;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.timestamp {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.8;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.section {
|
||||
background: white;
|
||||
padding: 25px;
|
||||
margin-bottom: 25px;
|
||||
border-radius: 10px;
|
||||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
color: #667eea;
|
||||
margin-bottom: 20px;
|
||||
font-size: 1.8em;
|
||||
border-bottom: 2px solid #667eea;
|
||||
padding-bottom: 10px;
|
||||
}
|
||||
|
||||
.summary-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.summary-card {
|
||||
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
|
||||
padding: 20px;
|
||||
border-radius: 8px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.summary-card.score {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.summary-card h3 {
|
||||
font-size: 0.9em;
|
||||
margin-bottom: 10px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.summary-card .value {
|
||||
font-size: 2.5em;
|
||||
font-weight: bold;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
.summary-card .label {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.grade {
|
||||
display: inline-block;
|
||||
padding: 5px 15px;
|
||||
border-radius: 20px;
|
||||
font-weight: bold;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.grade-A { background-color: #10b981; color: white; }
|
||||
.grade-B { background-color: #3b82f6; color: white; }
|
||||
.grade-C { background-color: #f59e0b; color: white; }
|
||||
.grade-D { background-color: #ef4444; color: white; }
|
||||
.grade-F { background-color: #991b1b; color: white; }
|
||||
|
||||
.recommendations {
|
||||
background-color: #fef3c7;
|
||||
border-left: 4px solid #f59e0b;
|
||||
padding: 15px;
|
||||
margin-top: 20px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.recommendations h3 {
|
||||
color: #92400e;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.recommendations ul {
|
||||
list-style-position: inside;
|
||||
color: #78350f;
|
||||
}
|
||||
|
||||
.recommendations li {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
margin-top: 15px;
|
||||
}
|
||||
|
||||
th, td {
|
||||
padding: 12px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid #e5e7eb;
|
||||
}
|
||||
|
||||
th {
|
||||
background-color: #f9fafb;
|
||||
font-weight: 600;
|
||||
color: #374151;
|
||||
}
|
||||
|
||||
tr:hover {
|
||||
background-color: #f9fafb;
|
||||
}
|
||||
|
||||
.status-badge {
|
||||
display: inline-block;
|
||||
padding: 4px 12px;
|
||||
border-radius: 12px;
|
||||
font-size: 0.85em;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.status-good { background-color: #d1fae5; color: #065f46; }
|
||||
.status-warning { background-color: #fed7aa; color: #92400e; }
|
||||
.status-poor { background-color: #fee2e2; color: #991b1b; }
|
||||
|
||||
.chart-container {
|
||||
margin: 20px 0;
|
||||
padding: 15px;
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.failed-case {
|
||||
background-color: #fef2f2;
|
||||
border-left: 4px solid #ef4444;
|
||||
padding: 15px;
|
||||
margin-bottom: 15px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
.failed-case h4 {
|
||||
color: #991b1b;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.failed-case .question {
|
||||
font-weight: 600;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.failed-case .metrics {
|
||||
font-size: 0.9em;
|
||||
color: #7f1d1d;
|
||||
}
|
||||
"""
|
||||
|
||||
def _generate_executive_summary_html(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""生成执行摘要HTML"""
|
||||
grade = self._score_to_grade(summary.overall_score)
|
||||
grade_class = f"grade-{grade[0]}"
|
||||
|
||||
success_rate = (summary.successful_questions / summary.total_questions * 100
|
||||
if summary.total_questions > 0 else 0)
|
||||
|
||||
html = f"""
|
||||
<div class="section">
|
||||
<h2>执行摘要</h2>
|
||||
<div class="summary-grid">
|
||||
<div class="summary-card score">
|
||||
<h3>整体评分</h3>
|
||||
<div class="value">{summary.overall_score:.1f}</div>
|
||||
<div class="grade {grade_class}">{grade}</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>总问题数</h3>
|
||||
<div class="value">{summary.total_questions}</div>
|
||||
<div class="label">评估问题</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>成功率</h3>
|
||||
<div class="value">{success_rate:.1f}%</div>
|
||||
<div class="label">{summary.successful_questions}/{summary.total_questions} 成功</div>
|
||||
</div>
|
||||
<div class="summary-card">
|
||||
<h3>平均响应时间</h3>
|
||||
<div class="value">{summary.avg_retrieval_time_ms + summary.avg_generation_time_ms:.0f}ms</div>
|
||||
<div class="label">检索+生成</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _generate_metrics_table_html(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""生成指标表格HTML"""
|
||||
rows = []
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
status = 'good' if stats.pass_rate >= 0.8 else 'warning' if stats.pass_rate >= 0.6 else 'poor'
|
||||
status_text = '优秀' if status == 'good' else '警告' if status == 'warning' else '较差'
|
||||
|
||||
rows.append(f"""
|
||||
<tr>
|
||||
<td>{self._translate_metric_name(metric_name)}</td>
|
||||
<td>{stats.mean:.3f}</td>
|
||||
<td>{stats.median:.3f}</td>
|
||||
<td>{stats.std_dev:.3f}</td>
|
||||
<td>{stats.pass_rate * 100:.1f}%</td>
|
||||
<td><span class="status-badge status-{status}">{status_text}</span></td>
|
||||
</tr>
|
||||
""")
|
||||
|
||||
html = f"""
|
||||
<div class="section">
|
||||
<h2>指标详情</h2>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>指标</th>
|
||||
<th>平均值</th>
|
||||
<th>中位数</th>
|
||||
<th>标准差</th>
|
||||
<th>通过率</th>
|
||||
<th>状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{''.join(rows)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _generate_failed_cases_html(
|
||||
self,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> str:
|
||||
"""生成失败案例HTML"""
|
||||
from .aggregator import ResultAggregator
|
||||
|
||||
aggregator = ResultAggregator()
|
||||
failed_cases = aggregator.identify_failed_cases(results, threshold=0.5)
|
||||
|
||||
if not failed_cases:
|
||||
return """
|
||||
<div class="section">
|
||||
<h2>失败案例</h2>
|
||||
<p>没有失败案例,所有问题都表现良好!</p>
|
||||
</div>
|
||||
"""
|
||||
|
||||
cases_html = []
|
||||
for case in failed_cases[:10]: # 只显示前10个
|
||||
if case['reason'] == 'evaluation_failed':
|
||||
cases_html.append(f"""
|
||||
<div class="failed-case">
|
||||
<h4>问题 #{case['question_index']}</h4>
|
||||
<div class="question">{case['question']}</div>
|
||||
<div class="metrics">错误: {case['error']}</div>
|
||||
</div>
|
||||
""")
|
||||
else:
|
||||
low_metrics_str = ', '.join(
|
||||
f"{k}: {v:.3f}" for k, v in case['low_metrics'].items()
|
||||
)
|
||||
cases_html.append(f"""
|
||||
<div class="failed-case">
|
||||
<h4>问题 #{case['question_index']}</h4>
|
||||
<div class="question">{case['question']}</div>
|
||||
<div class="metrics">低分指标: {low_metrics_str}</div>
|
||||
</div>
|
||||
""")
|
||||
|
||||
html = f"""
|
||||
<div class="section">
|
||||
<h2>失败案例 (前10个)</h2>
|
||||
{''.join(cases_html)}
|
||||
</div>
|
||||
"""
|
||||
return html
|
||||
|
||||
def _generate_charts_html(
|
||||
self,
|
||||
summary: EvaluationSummary,
|
||||
results: List[Dict[str, Any]]
|
||||
) -> str:
|
||||
"""生成图表HTML"""
|
||||
charts = []
|
||||
|
||||
# 1. 指标雷达图
|
||||
radar_chart = self._create_metrics_radar_chart(summary)
|
||||
charts.append(f"""
|
||||
<div class="section">
|
||||
<h2>指标雷达图</h2>
|
||||
<div id="radar-chart" class="chart-container"></div>
|
||||
<script>
|
||||
{radar_chart}
|
||||
</script>
|
||||
</div>
|
||||
""")
|
||||
|
||||
# 2. 指标分布柱状图
|
||||
bar_chart = self._create_metrics_bar_chart(summary)
|
||||
charts.append(f"""
|
||||
<div class="section">
|
||||
<h2>指标对比</h2>
|
||||
<div id="bar-chart" class="chart-container"></div>
|
||||
<script>
|
||||
{bar_chart}
|
||||
</script>
|
||||
</div>
|
||||
""")
|
||||
|
||||
# 3. 通过率饼图
|
||||
pie_chart = self._create_pass_rate_pie_chart(summary)
|
||||
charts.append(f"""
|
||||
<div class="section">
|
||||
<h2>整体通过率</h2>
|
||||
<div id="pie-chart" class="chart-container"></div>
|
||||
<script>
|
||||
{pie_chart}
|
||||
</script>
|
||||
</div>
|
||||
""")
|
||||
|
||||
return '\n'.join(charts)
|
||||
|
||||
def _create_metrics_radar_chart(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""创建指标雷达图"""
|
||||
categories = []
|
||||
values = []
|
||||
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
categories.append(self._translate_metric_name(metric_name))
|
||||
values.append(stats.mean)
|
||||
|
||||
# 闭合雷达图
|
||||
categories.append(categories[0])
|
||||
values.append(values[0])
|
||||
|
||||
data = {
|
||||
'type': 'scatterpolar',
|
||||
'r': values,
|
||||
'theta': categories,
|
||||
'fill': 'toself',
|
||||
'name': '指标得分'
|
||||
}
|
||||
|
||||
layout = {
|
||||
'polar': {
|
||||
'radialaxis': {
|
||||
'visible': True,
|
||||
'range': [0, 1]
|
||||
}
|
||||
},
|
||||
'showlegend': False
|
||||
}
|
||||
|
||||
return f"""
|
||||
var data = [{json.dumps(data)}];
|
||||
var layout = {json.dumps(layout)};
|
||||
Plotly.newPlot('radar-chart', data, layout);
|
||||
"""
|
||||
|
||||
def _create_metrics_bar_chart(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""创建指标柱状图"""
|
||||
categories = []
|
||||
means = []
|
||||
pass_rates = []
|
||||
|
||||
for metric_name, stats in summary.metric_stats.items():
|
||||
categories.append(self._translate_metric_name(metric_name))
|
||||
means.append(stats.mean)
|
||||
pass_rates.append(stats.pass_rate)
|
||||
|
||||
trace1 = {
|
||||
'x': categories,
|
||||
'y': means,
|
||||
'name': '平均得分',
|
||||
'type': 'bar',
|
||||
'marker': {'color': '#667eea'}
|
||||
}
|
||||
|
||||
trace2 = {
|
||||
'x': categories,
|
||||
'y': pass_rates,
|
||||
'name': '通过率',
|
||||
'type': 'bar',
|
||||
'marker': {'color': '#764ba2'}
|
||||
}
|
||||
|
||||
layout = {
|
||||
'barmode': 'group',
|
||||
'yaxis': {'range': [0, 1], 'title': '得分'},
|
||||
'xaxis': {'title': '指标'}
|
||||
}
|
||||
|
||||
return f"""
|
||||
var data = [{json.dumps(trace1)}, {json.dumps(trace2)}];
|
||||
var layout = {json.dumps(layout)};
|
||||
Plotly.newPlot('bar-chart', data, layout);
|
||||
"""
|
||||
|
||||
def _create_pass_rate_pie_chart(
|
||||
self,
|
||||
summary: EvaluationSummary
|
||||
) -> str:
|
||||
"""创建通过率饼图"""
|
||||
data = {
|
||||
'values': [summary.successful_questions, summary.failed_questions],
|
||||
'labels': ['成功', '失败'],
|
||||
'type': 'pie',
|
||||
'marker': {
|
||||
'colors': ['#10b981', '#ef4444']
|
||||
}
|
||||
}
|
||||
|
||||
layout = {
|
||||
'showlegend': True
|
||||
}
|
||||
|
||||
return f"""
|
||||
var data = [{json.dumps(data)}];
|
||||
var layout = {json.dumps(layout)};
|
||||
Plotly.newPlot('pie-chart', data, layout);
|
||||
"""
|
||||
|
||||
def create_trend_chart(
|
||||
self,
|
||||
history_data: List[Dict[str, Any]],
|
||||
output_path: str
|
||||
) -> None:
|
||||
"""
|
||||
创建趋势图
|
||||
|
||||
Args:
|
||||
history_data: 历史数据列表,每项包含 {timestamp, metrics}
|
||||
output_path: 输出路径
|
||||
"""
|
||||
if not history_data:
|
||||
raise ValueError("History data cannot be empty")
|
||||
|
||||
# 提取时间戳和指标
|
||||
timestamps = [item['timestamp'] for item in history_data]
|
||||
|
||||
# 获取所有指标名称
|
||||
metric_names = set()
|
||||
for item in history_data:
|
||||
metric_names.update(item['metrics'].keys())
|
||||
|
||||
# 创建子图
|
||||
fig = make_subplots(
|
||||
rows=len(metric_names),
|
||||
cols=1,
|
||||
subplot_titles=[self._translate_metric_name(m) for m in metric_names],
|
||||
vertical_spacing=0.05
|
||||
)
|
||||
|
||||
# 为每个指标添加趋势线
|
||||
for idx, metric_name in enumerate(sorted(metric_names), start=1):
|
||||
values = [
|
||||
item['metrics'].get(metric_name, None)
|
||||
for item in history_data
|
||||
]
|
||||
|
||||
fig.add_trace(
|
||||
go.Scatter(
|
||||
x=timestamps,
|
||||
y=values,
|
||||
mode='lines+markers',
|
||||
name=self._translate_metric_name(metric_name),
|
||||
line=dict(width=2),
|
||||
marker=dict(size=8)
|
||||
),
|
||||
row=idx,
|
||||
col=1
|
||||
)
|
||||
|
||||
# 更新布局
|
||||
fig.update_layout(
|
||||
height=300 * len(metric_names),
|
||||
title_text="评估指标历史趋势",
|
||||
showlegend=False
|
||||
)
|
||||
|
||||
# 保存为HTML
|
||||
fig.write_html(output_path)
|
||||
|
||||
def _translate_metric_name(self, metric_name: str) -> str:
|
||||
"""翻译指标名称为中文"""
|
||||
translations = {
|
||||
'context_recall': '上下文召回率',
|
||||
'context_precision': '上下文精确率',
|
||||
'mrr': '平均倒数排名',
|
||||
'ndcg': '归一化折损累计增益',
|
||||
'faithfulness': '忠实度',
|
||||
'answer_relevancy': '答案相关性',
|
||||
'correctness': '正确性'
|
||||
}
|
||||
return translations.get(metric_name, metric_name)
|
||||
|
||||
def _score_to_grade(self, score: float) -> str:
|
||||
"""将分数转换为等级"""
|
||||
if score >= 90:
|
||||
return 'A (优秀)'
|
||||
elif score >= 80:
|
||||
return 'B (良好)'
|
||||
elif score >= 70:
|
||||
return 'C (中等)'
|
||||
elif score >= 60:
|
||||
return 'D (及格)'
|
||||
else:
|
||||
return 'F (不及格)'
|
||||
Reference in new issue
Block a user