EventDrive / scripts /evaluation_understanding.py
dylanorange's picture
Upload 5 files
4ceeb65 verified
Raw
History Blame Contribute Delete
11.2 kB
import argparse
import json
import re
from collections import defaultdict
from tqdm import tqdm
DEFAULT_IOU_THRESH = 0.6
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."""
return clean_text(text).lower()
def parse_bbox(bbox_str):
"""Parse prediction text in 'x,y,w,h' format."""
try:
nums = re.findall(r"[-+]?\d*\.?\d+", bbox_str)
if len(nums) < 4:
return None
nums = nums[:4]
x, y, w, h = map(float, nums)
if w <= 0 or h <= 0:
return None
return [x, y, w, h]
except Exception:
return None
def bbox_iou(box1, box2):
"""Compute IoU for boxes in [x, y, w, h] format."""
x1_min, y1_min = box1[0], box1[1]
x1_max, y1_max = box1[0] + box1[2], box1[1] + box1[3]
x2_min, y2_min = box2[0], box2[1]
x2_max, y2_max = box2[0] + box2[2], box2[1] + box2[3]
inter_x1 = max(x1_min, x2_min)
inter_y1 = max(y1_min, y2_min)
inter_x2 = min(x1_max, x2_max)
inter_y2 = min(y1_max, y2_max)
inter_w = max(0, inter_x2 - inter_x1)
inter_h = max(0, inter_y2 - inter_y1)
inter_area = inter_w * inter_h
area1 = box1[2] * box1[3]
area2 = box2[2] * box2[3]
union = area1 + area2 - inter_area
return inter_area / union if union > 0 else 0.0
def is_text_match(gt_text, pred_text):
"""Apply the lenient text matching rule to a split label-text answer."""
if not gt_text or not pred_text:
return False
gt = gt_text.strip().lower()
pred = pred_text.strip().lower()
gt = re.sub(r"\b(a|an|the)\b", "", gt)
pred = re.sub(r"\b(a|an|the)\b", "", pred)
gt = re.sub(r"[^a-z0-9\s]", " ", gt)
pred = re.sub(r"[^a-z0-9\s]", " ", pred)
gt = re.sub(r"\s+", " ", gt).strip()
pred = re.sub(r"\s+", " ", pred).strip()
gt_tokens = set(gt.split())
pred_tokens = set(pred.split())
overlap = len(gt_tokens & pred_tokens)
union = len(gt_tokens | pred_tokens)
return overlap / union > 0.8 if union else False
def group_split_samples(data):
choice_groups = {}
grounding_items = []
grounding_ids = set()
for item in data:
original_id = item.get("original_id")
subtask = item.get("subtask")
category = item.get("category", "Unknown")
if not original_id:
raise ValueError("Understanding sample is missing original_id")
if category.lower() == "grounding":
if subtask != "grounding":
raise ValueError(f"Missing or invalid grounding subtask for {original_id}: {subtask!r}")
if original_id in grounding_ids:
raise ValueError(f"Duplicate grounding sample for {original_id}")
grounding_ids.add(original_id)
grounding_items.append(item)
continue
if subtask not in CHOICE_SUBTASKS:
raise ValueError(f"Missing or invalid understanding QA subtask: {subtask!r}")
group = choice_groups.setdefault(original_id, {})
if subtask in group:
raise ValueError(f"Duplicate understanding subtask {subtask!r} for {original_id}")
group[subtask] = item
required = set(CHOICE_SUBTASKS)
for original_id, group in choice_groups.items():
if set(group) != required:
raise ValueError(f"Incomplete understanding subtask pair for {original_id}: {sorted(group)}")
return choice_groups, grounding_items
def evaluate(pred_json, iou_thresh=DEFAULT_IOU_THRESH):
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}")
choice_groups, grounding_items = group_split_samples(data)
category_stats = defaultdict(lambda: {"total": 0, "correct": 0})
mismatch_examples = []
qa_correct = 0
option_letter_correct = 0
label_text_correct = 0
label_text_exact_correct = 0
for original_id, pair in tqdm(choice_groups.items(), desc="Evaluating understanding QA 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 understanding 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 = label_item["conversations"][1]["value"]
pred_label = label_item.get("model_output", "")
if gt_letter is None or not normalize_label_text(gt_label):
raise ValueError(f"Invalid understanding ground truth for {original_id}")
is_letter_correct = gt_letter == pred_letter
is_label_correct = is_text_match(gt_label, pred_label)
is_label_exact = normalize_label_text(gt_label) == normalize_label_text(pred_label)
is_joint_correct = is_letter_correct and is_label_correct
category_stats[category]["total"] += 1
option_letter_correct += is_letter_correct
label_text_correct += is_label_correct
label_text_exact_correct += is_label_exact
if is_joint_correct:
qa_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": pred_label,
},
})
correct_gd = 0
iou_sum = 0.0
for item in tqdm(grounding_items, desc="Evaluating understanding grounding"):
category = item.get("category", "Grounding")
gt_bbox = item.get("gt_bbox", {})
try:
gt_box = [gt_bbox["x"], gt_bbox["y"], gt_bbox["w"], gt_bbox["h"]]
except (KeyError, TypeError) as exc:
raise ValueError(f"Invalid grounding ground truth for {item['original_id']}") from exc
pred_raw = item.get("model_output", "")
pred_box = parse_bbox(pred_raw)
category_stats[category]["total"] += 1
if pred_box is not None:
iou = bbox_iou(pred_box, gt_box)
iou_sum += iou
if iou >= iou_thresh:
correct_gd += 1
category_stats[category]["correct"] += 1
else:
mismatch_examples.append({
"original_id": item["original_id"],
"image": item["image"],
"category": category,
"gt_bbox": gt_box,
"pred_bbox": pred_box,
"iou": round(iou, 3),
})
else:
mismatch_examples.append({
"original_id": item["original_id"],
"image": item["image"],
"category": category,
"gt_bbox": gt_box,
"pred_bbox": "Invalid",
"iou": 0.0,
})
qa_total = len(choice_groups)
gd_total = len(grounding_items)
qa_acc = qa_correct / qa_total * 100 if qa_total else 0.0
option_letter_acc = option_letter_correct / qa_total * 100 if qa_total else 0.0
label_text_acc = label_text_correct / qa_total * 100 if qa_total else 0.0
label_text_exact_acc = label_text_exact_correct / qa_total * 100 if qa_total else 0.0
gd_acc = correct_gd / gd_total * 100 if gd_total else 0.0
avg_iou = iou_sum / gd_total if gd_total else 0.0
print("\n========== QA Part ==========")
print(f"Inference samples: {qa_total * 2}")
print(f"Original questions: {qa_total}")
print(f"Overall accuracy (option_letter + label_text): {qa_acc:.2f}%")
print(f"Option-letter accuracy: {option_letter_acc:.2f}%")
print(f"Label-text soft-match accuracy: {label_text_acc:.2f}%")
print(f"Label-text exact accuracy: {label_text_exact_acc:.2f}%")
print("\n========== Grounding Part ==========")
print(f"Samples: {gd_total}")
print(f"Accuracy (IoU >= {iou_thresh}): {gd_acc:.2f}%")
print(f"Average IoU: {avg_iou:.3f}")
print("\nCategory-wise 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 = {
"qa": {
"inference_samples": qa_total * 2,
"total": qa_total,
"correct": qa_correct,
"accuracy (%)": round(qa_acc, 2),
"option_letter_accuracy (%)": round(option_letter_acc, 2),
"label_text_accuracy (%)": round(label_text_acc, 2),
"label_text_exact_accuracy (%)": round(label_text_exact_acc, 2),
},
"grounding": {
"total": gd_total,
"correct": correct_gd,
"accuracy (%)": round(gd_acc, 2),
"average_iou": round(avg_iou, 3),
"iou_threshold": iou_thresh,
},
"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 understanding predictions.")
parser.add_argument("--pred-json", required=True, help="Path to split understanding JSON with model_output fields.")
parser.add_argument("--iou-thresh", type=float, default=DEFAULT_IOU_THRESH, help="IoU threshold for grounding.")
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
evaluate(args.pred_json, iou_thresh=args.iou_thresh)