AINativeBench / data /processed /RQ1 /SQLAssistant-MCP /evaluate_scores.py
王子睿
restructure + add files
8c10cf2
Raw
History Blame Contribute Delete
5.74 kB
#!/usr/bin/env python3
"""
Collect score statistics for SQLAssistant-MCP project across models.
Data source: "score" field in execution_log.json for each session.
"""
import json
from pathlib import Path
import csv
# Base directory and model list
BASE_DIR = Path("/Users/wzr/TOSEM-2025/RESULTS")
MODELS = [
"DeepSeek-R1",
"DeepSeek-V3-1",
"GPT-4o-mini",
"GPT-5",
"Gemini-2.5-flash",
"Gemini-2.5-flash-nothinking",
"Qwen3-235b",
]
PROJECT_NAME = "SQLAssistant-MCP"
def collect_scores():
"""Collect scores from all models (from execution_log.json score field)."""
results = {}
for model in MODELS:
test_results_dir = BASE_DIR / model / PROJECT_NAME / "test_results"
if not test_results_dir.exists():
print(f"[WARN] Model {model} test_results directory not found")
continue
scores = []
session_details = []
# Iterate through all session subdirectories
for session_dir in sorted(test_results_dir.iterdir()):
if not session_dir.is_dir():
continue
log_file = session_dir / "execution_log.json"
if not log_file.exists():
continue
try:
with open(log_file, "r", encoding="utf-8") as f:
log_data = json.load(f)
# Extract numeric score from execution_log.json score field
# Structure example: "score": {"total_score": 70, "max_score": 100, "percentage": 70, ...}
score_field = log_data.get("score")
score = None
if isinstance(score_field, (int, float)):
score = score_field
elif isinstance(score_field, dict):
# For SQLAssistant-MCP, use percentage as numeric score (0-100)
score = score_field.get("percentage")
if isinstance(score, (int, float)):
scores.append(score)
session_details.append(
{
"session": session_dir.name,
"score": score,
}
)
except Exception as e:
print(f"[ERROR] Reading {log_file}: {e}")
# Calculate statistics
if scores:
stats = {
"model": model,
"total_samples": len(scores),
"mean_score": sum(scores) / len(scores),
"min_score": min(scores),
"max_score": max(scores),
# For SQLAssistant-MCP, percentage max is 100
"perfect_count": sum(1 for s in scores if s == 100.0),
"perfect_rate": sum(1 for s in scores if s == 100.0)
/ len(scores)
* 100,
"scores": scores,
"session_details": session_details,
}
else:
stats = {
"model": model,
"total_samples": 0,
"mean_score": 0.0,
"min_score": 0.0,
"max_score": 0.0,
"perfect_count": 0,
"perfect_rate": 0.0,
"scores": [],
"session_details": [],
}
results[model] = stats
return results
def print_summary(results: dict):
"""Print statistics summary."""
print("\n" + "=" * 100)
print(f"Score Statistics - {PROJECT_NAME}")
print("=" * 100)
print(
f"\n{'Model':<35} {'Samples':<10} {'Mean':<12} {'Min':<10} {'Max':<10} {'Perfect':<10} {'Perfect%':<10}"
)
print("-" * 100)
for model, stats in results.items():
if stats["total_samples"] > 0:
print(
f"{model:<35} {stats['total_samples']:<10} "
f"{stats['mean_score']:<12.4f} {stats['min_score']:<10.4f} "
f"{stats['max_score']:<10.4f} {stats['perfect_count']:<10} "
f"{stats['perfect_rate']:<10.1f}%"
)
else:
print(f"{model:<35} {'No data':<10}")
print("=" * 100)
def save_results(results: dict):
"""Save results to files."""
output_dir = Path(__file__).parent
# Save detailed JSON
json_file = output_dir / "score_analysis.json"
with open(json_file, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2, ensure_ascii=False)
print(f"\n[OK] JSON results saved: {json_file}")
# Save CSV summary
csv_file = output_dir / "score_summary.csv"
with open(csv_file, "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(
[
"Model",
"Total_Samples",
"Mean_Score",
"Min_Score",
"Max_Score",
"Perfect_Count",
"Perfect_Rate(%)",
]
)
for model, stats in results.items():
if stats["total_samples"] > 0:
writer.writerow(
[
model,
stats["total_samples"],
f"{stats['mean_score']:.4f}",
f"{stats['min_score']:.4f}",
f"{stats['max_score']:.4f}",
stats["perfect_count"],
f"{stats['perfect_rate']:.2f}",
]
)
print(f"[OK] CSV summary saved: {csv_file}")
if __name__ == "__main__":
print(f"Starting score statistics for {PROJECT_NAME}...")
results = collect_scores()
print_summary(results)
save_results(results)
print("\n[OK] Analysis complete!")