File size: 10,451 Bytes
e4932aa |
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 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
#!/usr/bin/env python3
"""
Run Evaluation Pipeline
This orchestrates the evaluation workflow on existing final_response data:
1. Count tactic occurrences (count_tactics.py)
2. Generate evaluation metrics (evaluate_metrics.py)
3. Compare models (compare_models.py)
4. Generate CSV with simple metrics (generate_metrics_csv.py)
NOTE: This does NOT run the full 3-agent pipeline.
Use execute_pipeline.py separately to generate final_response data first.
Usage:
python run_evaluation.py [--skip-counting]
"""
import subprocess
import sys
from pathlib import Path
from datetime import datetime
import argparse
def find_project_root(start: Path) -> Path:
"""Find the project root by looking for common markers."""
for p in [start] + list(start.parents):
if (
(p / "final_response").exists()
or (p / "src").exists()
or (p / ".git").exists()
):
return p
return start.parent
class EvaluationRunner:
"""Orchestrates the evaluation workflow"""
def __init__(self, skip_counting: bool = False):
self.skip_counting = skip_counting
current_file = Path(__file__).resolve()
self.project_root = find_project_root(current_file.parent)
# Point to the evaluation/full_pipeline directory for scripts
self.eval_dir = self.project_root / "src" / "evaluation" / "full_pipeline"
# Output directory now in mordor_dataset/eval_output
self.output_dir = (
self.project_root / "mordor_dataset" / "eval_output" / "evaluation_results"
)
self.start_time = None
def print_header(self, step: str, description: str):
"""Print a formatted step header"""
print("\n" + "=" * 80)
print(f"STEP {step}: {description}")
print("=" * 80)
def run_command(self, description: str, cmd: list) -> bool:
"""Run a command and handle errors"""
print(f"\n{description}")
print(f"Command: {' '.join(str(c) for c in cmd)}\n")
try:
result = subprocess.run(cmd, check=True)
print(f"\n[SUCCESS] {description} completed")
return True
except subprocess.CalledProcessError as e:
print(f"\n[ERROR] {description} failed with exit code {e.returncode}")
return False
except Exception as e:
print(f"\n[ERROR] Unexpected error during {description}: {e}")
return False
def step_1_count_tactics(self) -> bool:
"""Step 1: Count tactic occurrences"""
self.print_header("1/3", "Counting Tactic Occurrences")
if self.skip_counting:
print("Skipping tactic counting (--skip-counting flag set)")
print("Using existing tactic_counts_summary.json")
return True
final_response_dir = (
self.project_root / "mordor_dataset" / "eval_output" / "final_response"
)
# Ensure output directory exists
self.output_dir.mkdir(exist_ok=True)
output_file = self.output_dir / "tactic_counts_summary.json"
if not final_response_dir.exists():
print(
f"[ERROR] final_response directory not found at: {final_response_dir}"
)
print(
"Run execute_pipeline_all_datasets.py first to generate analysis results"
)
return False
# Count response_analysis.json files
analysis_files = list(final_response_dir.rglob("response_analysis.json"))
if not analysis_files:
print(f"[ERROR] No response_analysis.json files found in final_response")
print(
"Run execute_pipeline_all_datasets.py first to generate analysis results"
)
return False
print(f"Found {len(analysis_files)} analysis files")
print(f"Output: {output_file}")
script_path = self.eval_dir / "count_tactics.py"
return self.run_command(
"Count tactic occurrences",
[sys.executable, str(script_path), "--output", str(output_file)],
)
def step_2_evaluate_metrics(self) -> bool:
"""Step 2: Generate evaluation metrics for each model"""
self.print_header("2/3", "Generating Evaluation Metrics")
tactic_counts_file = self.output_dir / "tactic_counts_summary.json"
output_file = self.output_dir / "evaluation_report.json"
if not tactic_counts_file.exists():
print(f"[ERROR] Tactic counts file not found: {tactic_counts_file}")
print("Run step 1 first or remove --skip-counting flag")
return False
print(f"Input: {tactic_counts_file}")
print(f"Output: {output_file}")
print(
"Note: Individual model reports will be saved as evaluation_report_[model_name].json"
)
script_path = self.eval_dir / "evaluate_metrics.py"
return self.run_command(
"Generate evaluation metrics for each model",
[
sys.executable,
str(script_path),
"--input",
str(tactic_counts_file),
"--output",
str(output_file),
],
)
def step_3_compare_models(self) -> bool:
"""Step 3: Compare models"""
self.print_header("3/4", "Comparing Models")
tactic_counts_file = self.output_dir / "tactic_counts_summary.json"
output_file = self.output_dir / "model_comparison.json"
if not tactic_counts_file.exists():
print(f"[ERROR] Tactic counts file not found: {tactic_counts_file}")
print("Run step 1 first or remove --skip-counting flag")
return False
print(f"Input: {tactic_counts_file}")
print(f"Output: {output_file}")
script_path = self.eval_dir / "compare_models.py"
return self.run_command(
"Compare models",
[
sys.executable,
str(script_path),
"--input",
str(tactic_counts_file),
"--output",
str(output_file),
],
)
def step_4_generate_csv(self) -> bool:
"""Step 4: Generate CSV with simple metrics"""
self.print_header("4/4", "Generating CSV Metrics")
tactic_counts_file = self.output_dir / "tactic_counts_summary.json"
output_file = self.output_dir / "model_metrics.csv"
if not tactic_counts_file.exists():
print(f"[ERROR] Tactic counts file not found: {tactic_counts_file}")
print("Run step 1 first or remove --skip-counting flag")
return False
print(f"Input: {tactic_counts_file}")
print(f"Output: {output_file}")
script_path = self.eval_dir / "generate_metrics_csv.py"
return self.run_command(
"Generate CSV with simple metrics (F1, accuracy, precision, recall)",
[
sys.executable,
str(script_path),
"--input",
str(tactic_counts_file),
"--output",
str(output_file),
],
)
def run(self) -> int:
"""Run the evaluation pipeline"""
self.start_time = datetime.now()
print("\n" + "=" * 80)
print("EVALUATION PIPELINE")
print("=" * 80)
print(f"Project Root: {self.project_root}")
print(f"Evaluation Dir: {self.eval_dir}")
print(f"Output Dir: {self.output_dir}")
print(f"Start Time: {self.start_time.strftime('%Y-%m-%d %H:%M:%S')}")
# Step 1: Count tactics
if not self.step_1_count_tactics():
print("\n[ERROR] Evaluation failed at Step 1")
return 1
# Step 2: Evaluate metrics
if not self.step_2_evaluate_metrics():
print("\n[ERROR] Evaluation failed at Step 2")
return 1
# Step 3: Compare models
if not self.step_3_compare_models():
print("\n[ERROR] Evaluation failed at Step 3")
return 1
# Step 4: Generate CSV metrics
if not self.step_4_generate_csv():
print("\n[ERROR] Evaluation failed at Step 4")
return 1
# Success summary
end_time = datetime.now()
duration = (end_time - self.start_time).total_seconds()
print("\n" + "=" * 80)
print("EVALUATION PIPELINE COMPLETED SUCCESSFULLY")
print("=" * 80)
print(f"Duration: {duration:.1f} seconds")
print(f"\nOutput Files:")
print(f" - {self.output_dir / 'tactic_counts_summary.json'}")
print(f" - {self.output_dir / 'evaluation_report.json'} (summary)")
print(
f" - {self.output_dir / 'evaluation_report_[model_name].json'} (per model)"
)
print(f" - {self.output_dir / 'model_comparison.json'}")
print(
f" - {self.output_dir / 'model_metrics.csv'} (simple metrics: F1, accuracy, precision, recall)"
)
print(f"\nAll outputs are now organized under: mordor_dataset/eval_output/")
print("=" * 80 + "\n")
return 0
def main():
parser = argparse.ArgumentParser(
description="Run evaluation pipeline on existing final_response data",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Run full evaluation (count tactics + evaluate metrics + compare models)
python run_evaluation.py
# Skip counting, only evaluate (use existing tactic_counts_summary.json)
python run_evaluation.py --skip-counting
Note: This does NOT run the 3-agent pipeline.
Use execute_pipeline_all_datasets.py separately to process mordor dataset files.
""",
)
parser.add_argument(
"--skip-counting",
action="store_true",
help="Skip counting tactics, use existing tactic_counts_summary.json",
)
args = parser.parse_args()
runner = EvaluationRunner(skip_counting=args.skip_counting)
exit_code = runner.run()
sys.exit(exit_code)
if __name__ == "__main__":
main()
|