File size: 7,342 Bytes
8c10cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#!/usr/bin/env python3
"""
Compute the success rate of each model for the SocialMediaManager-A2A task.

Success criteria: the `status` field in `metadata.json` equals "success".
(status="success" means a Shakespeare-style X post was generated and validated.)
"""

import json
import re
from pathlib import Path
from collections import defaultdict

# Base path 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 = "SocialMediaManager-A2A"


def check_status_success(metadata_file: Path) -> tuple[bool, dict]:
    """
    Check whether the `status` field in `metadata.json` equals "success".

    Args:
        metadata_file: Path to `metadata.json`

    Returns:
        (success: bool, metadata: dict) - Success flag and the loaded metadata
    """
    if not metadata_file.exists():
        return False, {}

    try:
        with open(metadata_file, "r", encoding="utf-8") as f:
            metadata = json.load(f)

        status = metadata.get("status", "unknown")
        return status == "success", metadata

    except Exception as e:
        print(f"  ❌ Error reading {metadata_file}: {e}")
        return False, {}


def analyze_model_results():
    """Analyze execution results for each model."""
    results = {}

    for model in MODELS:
        test_results_dir = BASE_DIR / model / PROJECT_NAME / "test_results"

        if not test_results_dir.exists():
            print(
                f"⚠️  test_results directory not found for model {model}: {test_results_dir}"
            )
            continue

        model_stats = {
            "success_count": 0,
            "failure_count": 0,
            "total_count": 0,
            "sessions": [],
        }

        # Iterate over all session subfolders
        for session_dir in sorted(test_results_dir.iterdir()):
            if not session_dir.is_dir():
                continue

            metadata_file = session_dir / "metadata.json"

            # `metadata.json` is required for evaluation
            if not metadata_file.exists():
                continue

            try:
                # Check whether status is success
                is_success, metadata = check_status_success(metadata_file)

                # Extract metadata fields
                topic = metadata.get("topic", "unknown")
                retry_count = metadata.get("retry_count", 0)
                valid = metadata.get("valid", False)
                duration = metadata.get("duration_seconds", 0)
                crew_retry_count = metadata.get("crew_retry_count", 0)
                status = metadata.get("status", "unknown")

                model_stats["total_count"] += 1
                if is_success:
                    model_stats["success_count"] += 1
                else:
                    model_stats["failure_count"] += 1

                # Build status description
                if is_success:
                    reason = f"✅ Success (RETRY {retry_count} times, crew RETRY {crew_retry_count} times)"
                else:
                    reason = f"❌ Failure: status={status}"

                model_stats["sessions"].append(
                    {
                        "session": session_dir.name,
                        "success": is_success,
                        "status": status,
                        "topic": (
                            topic[:80] if isinstance(topic, str) else str(topic)[:80]
                        ),
                        "retry_count": retry_count,
                        "crew_retry_count": crew_retry_count,
                        "valid": valid,
                        "duration_seconds": round(duration, 2),
                        "reason": reason,
                    }
                )

            except Exception as e:
                print(f"❌ Error processing {session_dir}: {e}")

        results[model] = model_stats

    return results


def print_summary(results):
    """Print the summary statistics."""
    print("\n" + "=" * 100)
    print(f"Model execution summary - {PROJECT_NAME}")
    print("Success criteria: status field in metadata.json equals 'success'")
    print("=" * 100 + "\n")

    # Header
    print(
        f"{'Model':<35} {'Total':<10} {'Success':<10} {'Failure':<10} {'Success Rate':<15}"
    )
    print("-" * 100)

    for model, stats in results.items():
        total = stats["total_count"]
        success = stats["success_count"]
        failure = stats["failure_count"]

        if total > 0:
            success_rate = (success / total) * 100
            print(
                f"{model:<35} {total:<10} {success:<10} {failure:<10} {success_rate:>6.1f}%"
            )
        else:
            print(f"{model:<35} {'No data':<10}")

    print("=" * 100)


def print_failure_details(results):
    """Print details for failure samples."""
    print("\n" + "=" * 100)
    print("Failure sample details")
    print("=" * 100 + "\n")

    for model, stats in results.items():
        failures = [s for s in stats["sessions"] if not s["success"]]
        if not failures:
            continue

        print(f"\n{model} - Failure samples: {len(failures)}")
        print("-" * 100)

        for i, session in enumerate(failures, 1):
            print(f"{i}. {session['session']}")
            print(f"   Topic: {session['topic']}")
            print(f"   Status: {session['status']}")
            print(f"   Reason: {session['reason']}")
            print()


def save_detailed_results(results, output_file="success_detailed_results.json"):
    """Save detailed results to a JSON file."""
    output_path = Path(__file__).parent / output_file
    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(results, f, indent=2, ensure_ascii=False)
    print(f"\n✅ Detailed results saved to: {output_path}")


def save_csv_summary(results, output_file="success_rate.csv"):
    """Save the summary to a CSV file."""
    import csv

    output_path = Path(__file__).parent / output_file
    with open(output_path, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(
            ["Model", "Total", "Success", "Failure", "Success_Rate(%)", "Criteria"]
        )

        for model, stats in results.items():
            total = stats["total_count"]
            success = stats["success_count"]
            failure = stats["failure_count"]
            success_rate = (success / total * 100) if total > 0 else 0

            writer.writerow(
                [
                    model,
                    total,
                    success,
                    failure,
                    f"{success_rate:.2f}",
                    "status='success' in metadata.json",
                ]
            )

    print(f"✅ CSV summary saved to: {output_path}")


if __name__ == "__main__":
    print(f"Starting success-rate analysis for {PROJECT_NAME}...")
    print("Success criteria: status field in metadata.json equals 'success'\n")

    results = analyze_model_results()
    print_summary(results)
    print_failure_details(results)
    save_detailed_results(results)
    save_csv_summary(results)

    print("\n Done!")