实现功能完整的 Web 展示系统,支持实时数据读取和版本对比分析。 主要功能: - 全局概览:8个系统排名、得分卡片、排名图表 - 系统对比:多系统对比、雷达图可视化 - 版本对比:ZHT vs ZHTv2 专项对比(+43.69%整体提升) - 问题横评:单个问题的多系统得分对比 技术栈: - 后端:Python + FastAPI + Uvicorn - 前端:React 18 + TypeScript + Vite + Ant Design + ECharts 核心特性: - 实时数据读取(无缓存,更新后刷新即可) - 完整的类型安全(Pydantic + TypeScript) - 丰富的可视化(ECharts 雷达图、柱状图) - 自动生成 API 文档(Swagger UI) 版本对比亮点: - 整体提升:+43.69% - Context Recall:+86.1% 提升 - 识别改进/退化问题 - 雷达图对比 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
218 lines
7.2 KiB
Python
218 lines
7.2 KiB
Python
"""
|
||
版本对比 API 路由(特别支持 ZHT vs ZHTv2 对比)
|
||
"""
|
||
from fastapi import APIRouter, HTTPException, Query
|
||
from typing import Dict, List
|
||
from src.api.services.data_loader import DataLoader
|
||
|
||
router = APIRouter(prefix="/version-compare", tags=["version-compare"])
|
||
|
||
# 创建数据加载器实例
|
||
loader = DataLoader()
|
||
|
||
|
||
def detect_version_pair(system1: str, system2: str) -> tuple:
|
||
"""
|
||
检测是否为版本对
|
||
|
||
Args:
|
||
system1: 系统1 ID
|
||
system2: 系统2 ID
|
||
|
||
Returns:
|
||
(base_name, version1, version2) 或 None
|
||
"""
|
||
# 提取基础系统名(去掉格式后缀)
|
||
base1 = system1.split('-')[0] if '-' in system1 else system1
|
||
base2 = system2.split('-')[0] if '-' in system2 else system2
|
||
|
||
# 定义版本对
|
||
version_pairs = [
|
||
('zht', 'zhtv2'),
|
||
('kbs', 'kbsv2'), # 预留
|
||
('coze', 'cozev2'), # 预留
|
||
]
|
||
|
||
for v1, v2 in version_pairs:
|
||
if {base1, base2} == {v1, v2}:
|
||
# 确定 v1 是旧版本,v2 是新版本
|
||
if base1 == v1:
|
||
return (v1, v2, system1, system2)
|
||
else:
|
||
return (v1, v2, system2, system1)
|
||
|
||
return None
|
||
|
||
|
||
@router.get("")
|
||
def compare_versions(
|
||
v1: str = Query(..., description="版本1系统ID,如 zht-text"),
|
||
v2: str = Query(..., description="版本2系统ID,如 zhtv2-text")
|
||
):
|
||
"""
|
||
版本对比(如 ZHT vs ZHTv2)
|
||
|
||
计算整体改进、各指标改进、按问题类型的改进情况
|
||
|
||
Args:
|
||
v1: 版本1的系统ID
|
||
v2: 版本2的系统ID
|
||
|
||
Returns:
|
||
对比结果,包含改进百分比和趋势
|
||
"""
|
||
try:
|
||
# 加载两个版本的数据
|
||
v1_data = loader.load_system_detail(v1)['results'][v1]
|
||
v2_data = loader.load_system_detail(v2)['results'][v2]
|
||
|
||
# 计算整体改进
|
||
v1_overall = v1_data.get('overall_score', 0.0)
|
||
v2_overall = v2_data.get('overall_score', 0.0)
|
||
overall_improvement = v2_overall - v1_overall
|
||
overall_improvement_pct = (overall_improvement / v1_overall * 100) if v1_overall > 0 else 0.0
|
||
|
||
# 计算各指标改进
|
||
metrics_improvement = {}
|
||
for metric in ['context_precision', 'context_recall', 'faithfulness', 'answer_relevance', 'answer_correctness']:
|
||
if metric in v1_data.get('positive_cases', {}) and metric in v2_data.get('positive_cases', {}):
|
||
v1_score = v1_data['positive_cases'][metric].get('mean', 0.0)
|
||
v2_score = v2_data['positive_cases'][metric].get('mean', 0.0)
|
||
|
||
improvement = v2_score - v1_score
|
||
percentage = (improvement / v1_score * 100) if v1_score > 0 else 0.0
|
||
|
||
metrics_improvement[metric] = {
|
||
'v1_score': round(v1_score, 4),
|
||
'v2_score': round(v2_score, 4),
|
||
'improvement': round(improvement, 4),
|
||
'percentage': round(percentage, 2)
|
||
}
|
||
|
||
# 按问题类型分析改进
|
||
type_improvement = {}
|
||
for qtype, scores in v1_data.get('analysis_by_question_type', {}).items():
|
||
v1_score = scores.get(v1, 0.0)
|
||
v2_score = v2_data.get('analysis_by_question_type', {}).get(qtype, {}).get(v2, 0.0)
|
||
|
||
improvement = v2_score - v1_score
|
||
type_improvement[qtype] = {
|
||
'v1_score': round(v1_score, 4),
|
||
'v2_score': round(v2_score, 4),
|
||
'improvement': round(improvement, 4)
|
||
}
|
||
|
||
# 识别改进和退化的问题
|
||
improved_questions = []
|
||
degraded_questions = []
|
||
|
||
if 'answer_correctness' in v1_data.get('positive_cases', {}):
|
||
v1_per_q = v1_data['positive_cases']['answer_correctness'].get('per_question', {})
|
||
v2_per_q = v2_data['positive_cases']['answer_correctness'].get('per_question', {})
|
||
|
||
for q_id in v1_per_q:
|
||
if q_id in v2_per_q:
|
||
v1_score = v1_per_q[q_id]
|
||
v2_score = v2_per_q[q_id]
|
||
|
||
# 提升/下降超过 10% 视为显著
|
||
if v2_score > v1_score * 1.1:
|
||
improved_questions.append({
|
||
'question_id': q_id,
|
||
'v1_score': round(v1_score, 4),
|
||
'v2_score': round(v2_score, 4),
|
||
'improvement': round(v2_score - v1_score, 4)
|
||
})
|
||
elif v2_score < v1_score * 0.9:
|
||
degraded_questions.append({
|
||
'question_id': q_id,
|
||
'v1_score': round(v1_score, 4),
|
||
'v2_score': round(v2_score, 4),
|
||
'decline': round(v1_score - v2_score, 4)
|
||
})
|
||
|
||
# 排序
|
||
improved_questions.sort(key=lambda x: x['improvement'], reverse=True)
|
||
degraded_questions.sort(key=lambda x: x['decline'], reverse=True)
|
||
|
||
return {
|
||
"success": True,
|
||
"data": {
|
||
'v1': {
|
||
'id': v1,
|
||
'score': round(v1_overall, 4)
|
||
},
|
||
'v2': {
|
||
'id': v2,
|
||
'score': round(v2_overall, 4)
|
||
},
|
||
'overall_improvement': {
|
||
'value': round(overall_improvement, 4),
|
||
'percentage': round(overall_improvement_pct, 2)
|
||
},
|
||
'metrics_improvement': metrics_improvement,
|
||
'type_improvement': type_improvement,
|
||
'improved_questions': improved_questions[:5], # 前5个改进最多的问题
|
||
'degraded_questions': degraded_questions[:5] # 前5个退化最多的问题
|
||
}
|
||
}
|
||
|
||
except FileNotFoundError as e:
|
||
raise HTTPException(status_code=404, detail=str(e))
|
||
except Exception as e:
|
||
raise HTTPException(status_code=500, detail=str(e))
|
||
|
||
|
||
@router.get("/quick-zht")
|
||
def quick_compare_zht(format: str = Query("text", description="数据格式:text 或 excel")):
|
||
"""
|
||
快速对比 ZHT vs ZHTv2
|
||
|
||
便捷接口,直接对比 ZHT 和 ZHTv2 的指定格式
|
||
|
||
Args:
|
||
format: 数据格式 (text/excel)
|
||
|
||
Returns:
|
||
对比结果
|
||
"""
|
||
v1 = f"zht-{format}"
|
||
v2 = f"zhtv2-{format}"
|
||
|
||
return compare_versions(v1=v1, v2=v2)
|
||
|
||
|
||
@router.get("/detect-pair")
|
||
def detect_if_version_pair(system1: str = Query(...), system2: str = Query(...)):
|
||
"""
|
||
检测两个系统是否为版本对
|
||
|
||
Args:
|
||
system1: 系统1 ID
|
||
system2: 系统2 ID
|
||
|
||
Returns:
|
||
是否为版本对及相关信息
|
||
"""
|
||
result = detect_version_pair(system1, system2)
|
||
|
||
if result:
|
||
base, old_ver, new_ver, sys1, sys2 = result
|
||
return {
|
||
"success": True,
|
||
"is_version_pair": True,
|
||
"data": {
|
||
"base_system": base,
|
||
"old_version": old_ver,
|
||
"new_version": new_ver,
|
||
"system1_full": sys1,
|
||
"system2_full": sys2
|
||
}
|
||
}
|
||
else:
|
||
return {
|
||
"success": True,
|
||
"is_version_pair": False,
|
||
"message": "这两个系统不是版本对"
|
||
}
|