| import argparse |
| import json |
| import re |
| from tqdm import tqdm |
|
|
|
|
| SUBTASK_CATEGORIES = { |
| "speed": ["KEEP", "ACCELERATE", "DECELERATE", "STOP"], |
| "path": ["LEFT", "RIGHT", "STRAIGHT", "UNKNOWN"], |
| } |
| REQUIRED_SUBTASKS = set(SUBTASK_CATEGORIES) |
|
|
|
|
| def clean_text(s: str): |
| """Normalize whitespace and punctuation.""" |
| if not isinstance(s, str): |
| return "" |
| s = s.strip() |
| s = re.sub(r"[.\n\r]+", " ", s) |
| s = re.sub(r"\s+", " ", s) |
| return s.strip() |
|
|
|
|
| def parse_prediction(text, subtask): |
| """ |
| Parse one split-task prediction: |
| "B ACCELERATE" -> "ACCELERATE" |
| "C STRAIGHT" -> "STRAIGHT" |
| """ |
| if subtask not in SUBTASK_CATEGORIES: |
| raise ValueError(f"Unexpected prediction subtask: {subtask!r}") |
|
|
| text = clean_text(text).upper() |
| categories = SUBTASK_CATEGORIES[subtask] |
| matches = [ |
| word for word in categories |
| if re.search(rf"(?<![A-Z_]){re.escape(word)}(?![A-Z_])", text) |
| ] |
| return matches[0] if len(matches) == 1 else None |
|
|
|
|
| def group_split_samples(data): |
| groups = {} |
| for item in data: |
| original_id = item.get("original_id") |
| subtask = item.get("subtask") |
| if not original_id: |
| raise ValueError("Prediction sample is missing original_id") |
| if subtask not in SUBTASK_CATEGORIES: |
| raise ValueError(f"Missing or invalid prediction subtask: {subtask!r}") |
|
|
| group = groups.setdefault(original_id, {}) |
| if subtask in group: |
| raise ValueError(f"Duplicate prediction subtask {subtask!r} for {original_id}") |
| group[subtask] = item |
|
|
| for original_id, group in groups.items(): |
| if set(group) != REQUIRED_SUBTASKS: |
| raise ValueError(f"Incomplete prediction subtask pair for {original_id}: {sorted(group)}") |
| return groups |
|
|
|
|
| def evaluate(pred_json): |
| with open(pred_json, "r", encoding="utf-8") as f: |
| data = json.load(f) |
|
|
| if not data: |
| raise ValueError(f"No samples found in {pred_json}") |
|
|
| groups = group_split_samples(data) |
| totals = {subtask: 0 for subtask in SUBTASK_CATEGORIES} |
| correct = {subtask: 0 for subtask in SUBTASK_CATEGORIES} |
| classwise = { |
| subtask: {category: {"total": 0, "correct": 0} for category in categories} |
| for subtask, categories in SUBTASK_CATEGORIES.items() |
| } |
| mismatch_examples = [] |
| joint_correct = 0 |
|
|
| for original_id, group in tqdm(groups.items(), desc="Evaluating prediction pairs"): |
| is_joint_correct = True |
| for subtask, item in group.items(): |
| gt_raw = item["conversations"][1]["value"] |
| pred_raw = item.get("model_output", "") |
|
|
| gt = parse_prediction(gt_raw, subtask) |
| pred = parse_prediction(pred_raw, subtask) |
| if gt is None: |
| raise ValueError(f"Invalid {subtask} ground-truth answer: {gt_raw!r}") |
|
|
| totals[subtask] += 1 |
| classwise[subtask][gt]["total"] += 1 |
| is_correct = gt == pred |
| is_joint_correct = is_joint_correct and is_correct |
| if is_correct: |
| correct[subtask] += 1 |
| classwise[subtask][gt]["correct"] += 1 |
| else: |
| mismatch_examples.append({ |
| "original_id": original_id, |
| "image": item["image"], |
| "bbox_2d": item.get("bbox_2d", {}), |
| "subtask": subtask, |
| "gt": gt, |
| "pred": pred, |
| "model_output": pred_raw, |
| }) |
| joint_correct += is_joint_correct |
|
|
| total = sum(totals.values()) |
| original_questions = len(groups) |
| overall_acc = sum(correct.values()) / total * 100 |
| joint_acc = joint_correct / original_questions * 100 |
|
|
| print(f"\nTotal samples: {total}") |
| print(f"Original questions: {original_questions}") |
| for subtask in SUBTASK_CATEGORIES: |
| accuracy = correct[subtask] / totals[subtask] * 100 if totals[subtask] else 0.0 |
| print(f"{subtask.upper()} accuracy: {accuracy:.2f}% ({correct[subtask]}/{totals[subtask]})") |
| print(f"Overall accuracy: {overall_acc:.2f}%") |
| print(f"Joint accuracy: {joint_acc:.2f}% ({joint_correct}/{original_questions})") |
| print(f"Wrong examples: {len(mismatch_examples)}") |
|
|
| result_summary = { |
| "total": total, |
| "original_questions": original_questions, |
| "overall_accuracy (%)": round(overall_acc, 2), |
| "joint_correct": joint_correct, |
| "joint_accuracy (%)": round(joint_acc, 2), |
| "subtasks": { |
| subtask: { |
| "total": totals[subtask], |
| "accuracy (%)": round(correct[subtask] / totals[subtask] * 100, 2) if totals[subtask] else None, |
| "classwise": { |
| category: round(stats["correct"] / stats["total"] * 100, 2) if stats["total"] else None |
| for category, stats in classwise[subtask].items() |
| }, |
| } |
| for subtask in SUBTASK_CATEGORIES |
| }, |
| } |
|
|
| error_path = pred_json.replace(".json", "_errors.json") |
| with open(error_path, "w", encoding="utf-8") as f: |
| json.dump(mismatch_examples, f, indent=2, ensure_ascii=False) |
|
|
| result_path = pred_json.replace(".json", "_accuracy.json") |
| with open(result_path, "w", encoding="utf-8") as f: |
| json.dump(result_summary, f, indent=2, ensure_ascii=False) |
|
|
| print(f"\nError samples saved to {error_path}") |
| print(f"Accuracy summary saved to {result_path}") |
|
|
| return result_summary |
|
|
|
|
| def parse_args(): |
| parser = argparse.ArgumentParser(description="Evaluate EventDrive prediction task results.") |
| parser.add_argument("--pred-json", required=True, help="Path to prediction JSON with model_output fields.") |
| return parser.parse_args() |
|
|
|
|
| if __name__ == "__main__": |
| args = parse_args() |
| evaluate(args.pred_json) |
|
|