EventDrive / scripts /evaluation_perception.py
dylanorange's picture
Upload 5 files
4ceeb65 verified
Raw
History Blame Contribute Delete
6.15 kB
import argparse
import json
import re
from collections import defaultdict
from tqdm import tqdm
CHOICE_SUBTASKS = ("option_letter", "label_text")
def clean_text(s: str):
"""Normalize whitespace and common answer prefixes."""
if not isinstance(s, str):
return ""
s = s.strip()
s = s.replace("Answer:", "").replace("answer:", "")
s = re.sub(r"[.\n\r]+", "", s)
s = re.sub(r"\s+", " ", s)
return s.strip()
def parse_option_letter(text):
"""Parse a split option-letter answer such as 'B'."""
text = clean_text(text)
return text.upper() if re.fullmatch(r"[A-Da-d]", text) else None
def normalize_label_text(text):
"""Normalize a split label-text answer such as 'Low light'."""
return clean_text(text).lower()
def group_split_choices(data):
groups = {}
for item in data:
original_id = item.get("original_id")
subtask = item.get("subtask")
if not original_id:
raise ValueError("Perception sample is missing original_id")
if subtask not in CHOICE_SUBTASKS:
raise ValueError(f"Missing or invalid perception subtask: {subtask!r}")
group = groups.setdefault(original_id, {})
if subtask in group:
raise ValueError(f"Duplicate perception subtask {subtask!r} for {original_id}")
group[subtask] = item
required = set(CHOICE_SUBTASKS)
for original_id, group in groups.items():
if set(group) != required:
raise ValueError(f"Incomplete perception 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_choices(data)
total, correct = 0, 0
option_letter_correct, label_text_correct = 0, 0
mismatch_examples = []
category_stats = defaultdict(lambda: {"total": 0, "correct": 0})
for original_id, pair in tqdm(groups.items(), desc="Evaluating perception pairs"):
letter_item = pair["option_letter"]
label_item = pair["label_text"]
category = letter_item.get("category", "Unknown")
if label_item.get("category", "Unknown") != category:
raise ValueError(f"Mismatched perception categories for {original_id}")
gt_letter = parse_option_letter(letter_item["conversations"][1]["value"])
pred_letter = parse_option_letter(letter_item.get("model_output", ""))
gt_label = normalize_label_text(label_item["conversations"][1]["value"])
pred_label = normalize_label_text(label_item.get("model_output", ""))
if gt_letter is None or not gt_label:
raise ValueError(f"Invalid perception ground truth for {original_id}")
is_letter_correct = gt_letter == pred_letter
is_label_correct = gt_label == pred_label
is_joint_correct = is_letter_correct and is_label_correct
total += 1
category_stats[category]["total"] += 1
option_letter_correct += is_letter_correct
label_text_correct += is_label_correct
if is_joint_correct:
correct += 1
category_stats[category]["correct"] += 1
else:
mismatch_examples.append({
"original_id": original_id,
"image": letter_item["image"],
"category": category,
"gt": {
"option_letter": gt_letter,
"label_text": gt_label,
},
"pred": {
"option_letter": pred_letter,
"label_text": pred_label,
},
"model_output": {
"option_letter": letter_item.get("model_output", ""),
"label_text": label_item.get("model_output", ""),
},
})
overall_acc = correct / total * 100
option_letter_acc = option_letter_correct / total * 100
label_text_acc = label_text_correct / total * 100
print(f"\nInference samples: {len(data)}")
print(f"Original questions: {total}")
print(f"Overall accuracy (option_letter + label_text): {overall_acc:.2f}%")
print(f"Option-letter accuracy: {option_letter_acc:.2f}%")
print(f"Label-text accuracy: {label_text_acc:.2f}%")
print(f"Wrong original questions: {len(mismatch_examples)}")
print("\nCategory-wise Joint Accuracy:")
category_acc = {}
for category, stats in category_stats.items():
acc = stats["correct"] / stats["total"] * 100 if stats["total"] else 0.0
category_acc[category] = {
"total": stats["total"],
"correct": stats["correct"],
"accuracy (%)": round(acc, 2),
}
print(f" {category:20s}: {acc:5.2f}% ({stats['correct']}/{stats['total']})")
result_summary = {
"overall": {
"inference_samples": len(data),
"total": total,
"correct": correct,
"accuracy (%)": round(overall_acc, 2),
"option_letter_accuracy (%)": round(option_letter_acc, 2),
"label_text_accuracy (%)": round(label_text_acc, 2),
},
"categories": category_acc,
}
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 split EventDrive perception predictions.")
parser.add_argument("--pred-json", required=True, help="Path to split perception JSON with model_output fields.")
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
evaluate(args.pred_json)