| import argparse |
| import json |
| import re |
| from tqdm import tqdm |
|
|
|
|
| HIGHLEVEL_CATEGORIES = { |
| "speed": ["KEEP", "ACCELERATE", "DECELERATE", "STOP"], |
| "path": ["STRAIGHT", "LEFT_TURN", "RIGHT_TURN", "LEFT_CHANGE", "RIGHT_CHANGE", "UNKNOWN"], |
| } |
| REQUIRED_HIGHLEVEL_SUBTASKS = set(HIGHLEVEL_CATEGORIES) |
|
|
|
|
| def get_numpy(): |
| import numpy as np |
| return np |
|
|
|
|
| def clean_text(s: str): |
| 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_highlevel_prediction(text, subtask): |
| if subtask not in HIGHLEVEL_CATEGORIES: |
| raise ValueError(f"Unexpected planning high-level subtask: {subtask!r}") |
|
|
| text = clean_text(text).upper() |
| categories = HIGHLEVEL_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 parse_traj(text): |
| """ |
| Parse trajectory text like "[0.001, -0.002], [0.003, -0.004]". |
| Returns an array with shape [N, 2]. |
| """ |
| np = get_numpy() |
| if not isinstance(text, str): |
| return np.zeros((0, 2)) |
|
|
| |
| nums = re.findall(r"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?", text) |
| if len(nums) < 2: |
| return np.zeros((0, 2)) |
| if len(nums) % 2 != 0: |
| return np.zeros((0, 2)) |
|
|
| arr = np.array(nums, dtype=float) |
| arr = arr.reshape(-1, 2) |
| return arr |
|
|
| def compute_l2_error(gt, pred, dt=0.5): |
| """ |
| gt, pred: np.array of shape [10, 2] |
| Returns: {1s, 3s, 5s, mean} |
| """ |
| if gt.shape != pred.shape or gt.shape[0] == 0: |
| return {"1s": None, "3s": None, "5s": None, "mean": None} |
|
|
| np = get_numpy() |
| errors = np.linalg.norm(gt - pred, axis=1) |
| time_horizons = [1.0, 3.0, 5.0] |
| results = {} |
| for t in time_horizons: |
| idx = int(t / dt) - 1 |
| idx = min(idx, len(errors) - 1) |
| results[f"{t:.0f}s"] = float(errors[idx]) |
| results["mean"] = float(np.mean(errors)) |
| return results |
|
|
|
|
| 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}") |
|
|
| highlevel_totals = {subtask: 0 for subtask in HIGHLEVEL_CATEGORIES} |
| highlevel_correct = {subtask: 0 for subtask in HIGHLEVEL_CATEGORIES} |
| highlevel_classwise = { |
| subtask: {category: {"total": 0, "correct": 0} for category in categories} |
| for subtask, categories in HIGHLEVEL_CATEGORIES.items() |
| } |
| highlevel_groups = {} |
| trajectory_items = [] |
| traj_errors = [] |
|
|
| mismatch_high = [] |
|
|
| for item in data: |
| category = item["category"] |
|
|
| if category == "Planning-HighLevel": |
| original_id = item.get("original_id") |
| subtask = item.get("subtask") |
| if not original_id: |
| raise ValueError("Planning high-level sample is missing original_id") |
| if subtask not in HIGHLEVEL_CATEGORIES: |
| raise ValueError(f"Missing or invalid planning high-level subtask: {subtask!r}") |
|
|
| group = highlevel_groups.setdefault(original_id, {}) |
| if subtask in group: |
| raise ValueError(f"Duplicate planning high-level subtask {subtask!r} for {original_id}") |
| group[subtask] = item |
| elif category == "Planning-Trajectory": |
| trajectory_items.append(item) |
| else: |
| raise ValueError(f"Unexpected planning category: {category!r}") |
|
|
| for original_id, group in highlevel_groups.items(): |
| if set(group) != REQUIRED_HIGHLEVEL_SUBTASKS: |
| raise ValueError(f"Incomplete planning high-level subtask pair for {original_id}: {sorted(group)}") |
|
|
| joint_correct = 0 |
| for original_id, group in tqdm(highlevel_groups.items(), desc="Evaluating planning intent 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_highlevel_prediction(gt_raw, subtask) |
| pred = parse_highlevel_prediction(pred_raw, subtask) |
| if gt is None: |
| raise ValueError(f"Invalid planning {subtask} ground-truth answer: {gt_raw!r}") |
|
|
| highlevel_totals[subtask] += 1 |
| highlevel_classwise[subtask][gt]["total"] += 1 |
| is_correct = gt == pred |
| is_joint_correct = is_joint_correct and is_correct |
| if is_correct: |
| highlevel_correct[subtask] += 1 |
| highlevel_classwise[subtask][gt]["correct"] += 1 |
| else: |
| mismatch_high.append({ |
| "original_id": original_id, |
| "image": item["image"], |
| "subtask": subtask, |
| "gt": gt, |
| "pred": pred, |
| "model_output": pred_raw, |
| }) |
| joint_correct += is_joint_correct |
|
|
| for item in tqdm(trajectory_items, desc="Evaluating planning trajectories"): |
| gt_raw = item["conversations"][1]["value"] |
| pred_raw = item.get("model_output", "") |
| gt_traj = parse_traj(gt_raw) |
| pred_traj = parse_traj(pred_raw) |
| if gt_traj.shape[0] != 10: |
| raise ValueError(f"Invalid planning trajectory ground truth for {item['image']}: {gt_raw!r}") |
| if pred_traj.shape[0] != 10: |
| raise ValueError( |
| f"Invalid planning trajectory prediction for {item['image']}: " |
| f"expected exactly 10 waypoints, got {pred_traj.shape[0]}" |
| ) |
| traj_errors.append(compute_l2_error(gt_traj, pred_traj)) |
|
|
| results = {} |
| total_high = sum(highlevel_totals.values()) |
| original_questions = len(highlevel_groups) |
|
|
| if total_high > 0: |
| results["HighLevel"] = { |
| "total": total_high, |
| "original_questions": original_questions, |
| "overall_accuracy (%)": round(sum(highlevel_correct.values()) / total_high * 100, 2), |
| "joint_correct": joint_correct, |
| "joint_accuracy (%)": round(joint_correct / original_questions * 100, 2), |
| "subtasks": { |
| subtask: { |
| "total": highlevel_totals[subtask], |
| "accuracy (%)": round(highlevel_correct[subtask] / highlevel_totals[subtask] * 100, 2) |
| if highlevel_totals[subtask] |
| else None, |
| "classwise": { |
| category: round(stats["correct"] / stats["total"] * 100, 2) if stats["total"] else None |
| for category, stats in highlevel_classwise[subtask].items() |
| }, |
| } |
| for subtask in HIGHLEVEL_CATEGORIES |
| }, |
| } |
|
|
| total_traj = len(trajectory_items) |
| if total_traj > 0: |
| results["Trajectory"] = { |
| "total": total_traj, |
| "valid_predictions": total_traj, |
| "invalid_predictions": 0, |
| } |
| if traj_errors: |
| np = get_numpy() |
| traj_errs_np = { |
| k: np.mean([error[k] for error in traj_errors if error[k] is not None]) |
| for k in ["1s", "3s", "5s", "mean"] |
| } |
| results["Trajectory"]["avg_L2_error_m"] = {k: round(v, 4) for k, v in traj_errs_np.items()} |
|
|
| print("\n=== Evaluation Summary ===") |
| print(json.dumps(results, indent=2)) |
|
|
| result_path = pred_json.replace(".json", "_eval_results.json") |
| with open(result_path, "w", encoding="utf-8") as f: |
| json.dump(results, f, indent=2, ensure_ascii=False) |
|
|
| with open(pred_json.replace(".json", "_highlevel_mismatch.json"), "w", encoding="utf-8") as f: |
| json.dump(mismatch_high, f, indent=2, ensure_ascii=False) |
| print(f"Evaluation summary saved to {result_path}") |
|
|
| return results |
|
|
|
|
| def parse_args(): |
| parser = argparse.ArgumentParser(description="Evaluate EventDrive planning 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) |
|
|