""" ClockBench 공식 채점 로직(aleksafar/clockbench/clockbench_grade.py 기반)을 적용한 채점 스크립트. 산출 지표 (ClockBench 논문과 동일): - per_task_accuracy_abs: 문항별 전체 정확도 (answer_time / shift / angle / zone / hands) - answer_time_validity_breakdown: Valid 시계 정확도 / Invalid 시계 정확도 / 전체 정확도 - answer_hands_accuracy: Q4 시침·분침·초침 유무의 바늘별 및 전체 일치율 - predicted_invalid: 모델이 invalid로 예측한 비율 - conditional_accuracy_given_valid_answer_time_correct: Q1을 맞힌 유효 시계에서 후속 시각 문항(Q2·Q3 및 이전 데이터셋의 시간대 변환) 정확도 - answer_time_delta_seconds_on_incorrect_valid_circular: 틀린 Valid 시계들의 12시간 시계판 기준 원형 오차 평균 및 중앙값 사용 예시: python clockbench_grade.py --answers input/answers.json --predictions output/predictions.json """ from __future__ import annotations import argparse import ast import json import math import re from collections import OrderedDict from pathlib import Path from statistics import median from typing import Any HAND_FIELDS = ("hour_hand", "minute_hand", "second_hand") FIELDS_BY_TASK = { "answer_hands": list(HAND_FIELDS), "answer_time": ["valid", "hours", "minutes", "seconds", "date", "month", "weekday"], "answer_shift": ["valid", "hours", "minutes", "seconds"], "answer_angle": ["valid", "hours", "minutes", "seconds"], "answer_zone": ["valid", "hours", "minutes", "seconds"], } ALL_TASKS = ["answer_time", "answer_shift", "answer_angle", "answer_zone", "answer_hands"] def load_ordered(path: Path) -> OrderedDict[str, Any]: with path.open("r", encoding="utf-8") as f: return json.load(f, object_pairs_hook=OrderedDict) def parse_obj(v: Any) -> dict[str, Any]: """공식 ClockBench 파싱 로직 + 에러/미파싱 응답 안전 처리.""" if isinstance(v, dict): return v if v is None: return {} s = str(v).strip() if not s: return {} s = re.sub(r".*?", "", s, flags=re.I | re.S).strip() if s.startswith("```"): s = re.sub(r"^```(?:json|javascript|js)?\s*|\s*```$", "", s, flags=re.I | re.S).strip() if re.fullmatch(r"invalid", s, re.I): return { "valid": False, "hours": False, "minutes": False, "seconds": False, } direct = re.fullmatch(r"(\d{1,2}):([0-5]\d)(?::([0-5]\d))?(?:\s*[AP]M)?", s, re.I) if direct and int(direct[1]) <= 24: return { "valid": True, "hours": int(direct[1]), "minutes": int(direct[2]), "seconds": int(direct[3]) if direct[3] is not None else False, "date": False, "month": False, "weekday": False, } m = re.search(r"\{.*\}", s, flags=re.S) if m: s = m.group(0) try: parsed = json.loads(s) return parsed if isinstance(parsed, dict) else {} except json.JSONDecodeError: pass s2 = re.sub(r",(\s*[}\]])", r"\1", s) s2 = re.sub(r'(?m)(?<=\{|,)\s*([A-Za-z_]\w*)\s*:', r'"\1":', s2) try: parsed = json.loads(s2) return parsed if isinstance(parsed, dict) else {} except json.JSONDecodeError: pass s3 = re.sub(r"\btrue\b", "True", s2, flags=re.I) s3 = re.sub(r"\bfalse\b", "False", s3, flags=re.I) s3 = re.sub(r"\bnull\b", "None", s3, flags=re.I) try: parsed = ast.literal_eval(s3) return parsed if isinstance(parsed, dict) else {} except Exception: return {} def is_num(x: Any) -> bool: return isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x) def as_int_or_none(x: Any) -> int | None: if is_num(x): return int(x) if x == int(x) else None if isinstance(x, str): xs = x.strip() if re.fullmatch(r"-?\d+", xs): return int(xs) return None def match_value(expected: Any, got: Any) -> bool: if isinstance(expected, str): return isinstance(got, str) and expected.strip().casefold() == str(got).strip().casefold() if isinstance(expected, (bool, type(None))): # 공식 clockbench_grade.py 동작 유지 (False/True/None 비교) if expected is False and got is None: return False return expected == got if is_num(expected): gi = as_int_or_none(got) return gi is not None and gi == int(expected) if isinstance(expected, list) and expected: if len(expected) == 2 and all(is_num(x) for x in expected): gi = as_int_or_none(got) if gi is None: return False lo, hi = int(expected[0]), int(expected[1]) return lo <= gi <= hi choices = { int(x) for x in expected if is_num(x) or (isinstance(x, str) and re.fullmatch(r"-?\d+", x)) } gi = as_int_or_none(got) return gi is not None and gi in choices if isinstance(expected, dict) and expected: choice_set = set() for v in expected.values(): if is_num(v): choice_set.add(int(v)) elif isinstance(v, str) and re.fullmatch(r"-?\d+", v.strip()): choice_set.add(int(v.strip())) elif isinstance(v, list) and len(v) == 2 and all(is_num(x) for x in v): lo, hi = int(v[0]), int(v[1]) choice_set.update(range(lo, hi + 1)) gi = as_int_or_none(got) return (gi is not None and gi in choice_set) if choice_set else (expected == got) return expected == got def compare_hands(expected: dict[str, Any], got: dict[str, Any]) -> tuple[bool, dict[str, bool]]: if any(type(expected.get(key)) is not bool for key in HAND_FIELDS): raise ValueError("answer_hands labels must contain three JSON booleans") matches = {key: got.get(key) is expected[key] for key in HAND_FIELDS} return all(matches.values()), matches def normalize(ans: dict[str, Any], fields: list[str]) -> dict[str, Any]: return {f: ans.get(f, None) for f in fields} def match_field(field: str, expected: Any, got: Any) -> bool: if field == "hours": hour = as_int_or_none(got) if hour is None or not 0 <= hour <= 24: return False if isinstance(expected, str): expected = as_int_or_none(expected) # Try each valid notation for this dial position, including legacy answer ranges. return any(match_value(expected, h) for h in range(hour % 12, 25, 12)) if field == "seconds" and (expected is False or expected is None): return got is None or got is False return match_value(expected, got) def compare_entry(gt_obj: dict[str, Any], pred_obj: dict[str, Any], fields: list[str]) -> tuple[bool, OrderedDict[str, Any]]: g, p = normalize(gt_obj, fields), normalize(pred_obj, fields) details: OrderedDict[str, Any] = OrderedDict() details["valid"] = (g.get("valid"), p.get("valid")) if g.get("valid") is not p.get("valid"): details["reason"] = "validity_mismatch" return False, details if g.get("valid") is False: return True, details all_ok = True for f in fields: if f == "valid": continue ok = match_field(f, g.get(f), p.get(f)) details[f] = (g.get(f), p.get(f), ok) all_ok = all_ok and ok return all_ok, details def midpoint_int(lo: int, hi: int) -> int: return int(round((int(lo) + int(hi)) / 2.0)) def scalar_expected(x: Any) -> int | None: if x is False or x is None: return 0 xi = as_int_or_none(x) if xi is not None: return xi if ( isinstance(x, list) and len(x) == 2 and as_int_or_none(x[0]) is not None and as_int_or_none(x[1]) is not None ): return midpoint_int(as_int_or_none(x[0]), as_int_or_none(x[1])) # type: ignore[arg-type] return None def scalar_got(x: Any, allow_missing_as_zero: bool = False) -> int | None: if x is False or x is None: return 0 if allow_missing_as_zero else None return as_int_or_none(x) def to_seconds(h: int | None, m: int | None, s: int | None, period_hours: int) -> int: hh = (int(h) if h is not None else 0) % period_hours mm = int(m) if m is not None else 0 ss = int(s) if s is not None else 0 return (hh * 3600 + mm * 60 + ss) % (period_hours * 3600) def dial_error_seconds(expected: dict[str, Any], got: dict[str, Any]) -> int | None: if expected.get("valid") is not True or got.get("valid") is not True: return None eh, em, es = (scalar_expected(expected.get(k)) for k in ("hours", "minutes", "seconds")) ph = as_int_or_none(got.get("hours")) pm = as_int_or_none(got.get("minutes")) ps = scalar_got(got.get("seconds"), allow_missing_as_zero=True) if None in (eh, em, es) or ph is None or not 0 <= ph <= 24 or pm is None or not 0 <= pm < 60: return None if ps is None or not 0 <= ps < 60: return None if expected.get("seconds") is False or expected.get("seconds") is None: ps = 0 # Only the displayed hands contribute to tolerance. diff = abs(to_seconds(eh, em, es, 12) - to_seconds(ph, pm, ps, 12)) return min(diff, 43200 - diff) def to_hm(seconds_or_none: float | None) -> dict[str, int] | None: if seconds_or_none is None: return None total = int(round(seconds_or_none)) return {"hours": total // 3600, "minutes": (total % 3600) // 60} def frac(n: int, d: int) -> float | None: return None if d == 0 else round(n / d, 4) def score_time_tiers(entries: list[dict[str, Any]]) -> dict[str, float | None]: counts = {"exact_12h": 0, "tol_1sec_12h": 0, "tol_1min_12h": 0} for entry in entries: exact = entry["correct"] delta = dial_error_seconds(entry["expected"], entry["got"]) counts["exact_12h"] += int(exact) for name, tolerance in (("tol_1sec_12h", 1), ("tol_1min_12h", 60)): counts[name] += int(exact or (delta is not None and delta <= tolerance)) return {k: frac(v, len(entries)) for k, v in counts.items()} def _fmt_time_short(obj: dict[str, Any]) -> str: if not isinstance(obj, dict) or not obj: return "응답 없음" if obj.get("valid") is False: return "invalid" h, m, s = obj.get("hours"), obj.get("minutes"), obj.get("seconds") if h is None or m is None: return "응답 없음" def _p(v: Any) -> str: if isinstance(v, list) and len(v) == 2: return f"{int(v[0]):02d}~{int(v[1]):02d}" if isinstance(v, dict): return "/".join(str(x) for x in v.values()) if is_num(v): return f"{int(v):02d}" return str(v) h_s = str(int(h)) if is_num(h) else _p(h) out = f"{h_s}:{_p(m)}" if s is not False and s is not None: out += f":{_p(s)}" return out def grade( answers_path: Path, predictions_path: Path, output_path: Path, summary_path: Path | None = None, ) -> OrderedDict[str, Any]: gt = load_ordered(answers_path) pred = load_ordered(predictions_path) ids = [k for k in gt.keys() if k in pred] if not ids: raise ValueError("정답 파일과 예측 파일 사이에 일치하는 항목 ID가 없습니다.") # 채점 가능한 task 결정 (정답과 예측 모두에 존재하는 task만, 기본 4개 또는 time-only 1개) task_keys = [ t for t in ALL_TASKS if any(gt[k].get(t) is not None for k in ids) and any(isinstance(pred[k], dict) and t in pred[k] for k in ids) ] if not task_keys: raise ValueError("채점할 문항(answer_time 등)을 찾을 수 없습니다. answers.json의 정답이 입력되었는지 확인하세요.") combined: OrderedDict[str, Any] = OrderedDict() totals = {t: {"correct": 0, "total": 0} for t in task_keys} print(f"Total matched clocks: {len(ids)} | Tasks: {', '.join(task_keys)}") for i, key in enumerate(ids, 1): combined[key] = OrderedDict() pred_item = pred[key] if isinstance(pred[key], dict) else {} for task in task_keys: fields = FIELDS_BY_TASK[task] g_raw = gt[key].get(task) p_raw = pred_item.get(task) if g_raw is None: continue g = parse_obj(g_raw) if g.get("valid") is True and (g.get("hours") is None or g.get("minutes") is None): raise ValueError(f"[{key}] {task}의 정답(hours/minutes)이 비어 있습니다. answers.json을 먼저 채워주세요.") p = parse_obj(p_raw) if task == "answer_hands": ok, details = compare_hands(g, p) else: ok, details = compare_entry(g, p, fields) combined[key][task] = OrderedDict([ ("expected", g), ("got", p), ("correct", ok), ("details", details), ]) totals[task]["total"] += 1 totals[task]["correct"] += int(ok) marks = ", ".join( f"{t}:{'O' if combined[key][t]['correct'] else 'X'}" for t in task_keys if t in combined[key] ) print(f"[{i:2d}/{len(ids)}] {key} -> {marks}") # --- Validity breakdown --- base_task = "answer_time" if "answer_time" in task_keys else task_keys[0] graded_base_ids = [k for k in ids if base_task in combined[k]] valid_total = sum(1 for k in graded_base_ids if combined[k][base_task]["expected"].get("valid") is True) invalid_total = sum(1 for k in graded_base_ids if combined[k][base_task]["expected"].get("valid") is False) total_correct_base = sum(1 for k in graded_base_ids if combined[k][base_task]["correct"]) valid_correct = sum( 1 for k in graded_base_ids if combined[k][base_task]["expected"].get("valid") is True and combined[k][base_task]["correct"] ) invalid_correct = sum( 1 for k in graded_base_ids if combined[k][base_task]["expected"].get("valid") is False and combined[k][base_task]["correct"] ) validity_breakdown = OrderedDict([ ("task", base_task), ("total_items", len(graded_base_ids)), ("total_correct", total_correct_base), ("valid", OrderedDict([ ("correct", valid_correct), ("total", valid_total), ("accuracy", frac(valid_correct, valid_total)), ])), ("invalid", OrderedDict([ ("correct", invalid_correct), ("total", invalid_total), ("accuracy", frac(invalid_correct, invalid_total)), ])), ]) # --- Follow-up conditional accuracy --- followups = [t for t in ("answer_shift", "answer_angle", "answer_zone") if t in task_keys] valid_time_correct_ids = [ k for k in graded_base_ids if combined[k][base_task]["correct"] and combined[k][base_task]["expected"].get("valid") is True ] den_vc = len(valid_time_correct_ids) cond_valid: OrderedDict[str, Any] = OrderedDict() cond_valid["denominator_valid_time_correct"] = den_vc for t in followups: eligible = [k for k in valid_time_correct_ids if t in combined[k]] num = sum(1 for k in eligible if combined[k][t]["correct"]) cond_valid[f"{t}_given_valid_time_correct"] = { "numerator": num, "denominator": len(eligible), "accuracy": frac(num, len(eligible)), } # --- Circular time delta on incorrect valid clocks --- deltas_circ: list[int] = [] excluded_alt = 0 skipped_incomplete = 0 for k in graded_base_ids: g = combined[k][base_task]["expected"] p = combined[k][base_task]["got"] if g.get("valid") is not True: continue if any(isinstance(g.get(f), dict) for f in ("hours", "minutes", "seconds")): excluded_alt += 1 continue if all(match_field(f, g.get(f), p.get(f)) for f in ("hours", "minutes", "seconds")): continue delta = dial_error_seconds(g, p) if delta is None: skipped_incomplete += 1 continue deltas_circ.append(delta) avg_delta_circ = round(sum(deltas_circ) / len(deltas_circ), 2) if deltas_circ else None med_delta_circ = round(median(deltas_circ), 2) if deltas_circ else None pred_invalid = sum( 1 for k in graded_base_ids if isinstance(combined[k][base_task]["got"], dict) and combined[k][base_task]["got"].get("valid") is False ) pct_invalid = round(100.0 * pred_invalid / len(graded_base_ids), 2) if graded_base_ids else 0.0 per_task_acc = { t: round(totals[t]["correct"] / max(1, totals[t]["total"]), 4) for t in task_keys } scores = OrderedDict([ ("per_task_accuracy_abs", per_task_acc), ("answer_time_validity_breakdown", validity_breakdown), ("predicted_invalid", { "count": pred_invalid, "percent_of_all_items": pct_invalid, }), ("conditional_accuracy_given_valid_answer_time_correct", cond_valid), ("answer_time_delta_seconds_on_incorrect_valid_circular", OrderedDict([ ("count_items", len(deltas_circ)), ("average_delta_seconds", avg_delta_circ), ("median_delta_seconds", med_delta_circ), ("average_delta_hm", to_hm(avg_delta_circ)), ("median_delta_hm", to_hm(med_delta_circ)), ("excluded_due_to_alternatives", excluded_alt), ("skipped_incomplete_after_normalization", skipped_incomplete), ])), ]) if "answer_hands" in task_keys: hand_entries = [combined[k]["answer_hands"] for k in ids if "answer_hands" in combined[k]] scores["answer_hands_accuracy"] = { "total": len(hand_entries), "all_hands": per_task_acc["answer_hands"], **{key: frac(sum(e["details"][key] for e in hand_entries), len(hand_entries)) for key in HAND_FIELDS}, } if task_keys == ["answer_hands"]: scores = OrderedDict((key, scores[key]) for key in ("per_task_accuracy_abs", "answer_hands_accuracy")) if "answer_time" in task_keys: scores["answer_time_12h_accuracy"] = score_time_tiers([combined[k]["answer_time"] for k in graded_base_ids]) combined["_scores"] = scores output_path.parent.mkdir(parents=True, exist_ok=True) with output_path.open("w", encoding="utf-8") as f: json.dump(combined, f, ensure_ascii=False, indent=2) if summary_path is not None: lines: list[str] = [] for k in ids: img_name = gt[k].get("_image", k) if isinstance(gt[k], dict) else k gt_time = _fmt_time_short(combined[k][base_task]["expected"]) if base_task in combined[k] else "시간 미입력" if task_keys == ["answer_hands"]: e = combined[k].get("answer_hands") if e is not None: lines.append(f"{img_name} hands={json.dumps(e['got'])} [{'O' if e['correct'] else 'X'}]") continue if len(task_keys) == 1: got_str = _fmt_time_short(combined[k][base_task]["got"]) mark = "O" if combined[k][base_task]["correct"] else "X" lines.append(f"{img_name} ({gt_time}): {got_str} [{mark}]") else: parts = [] for short, tk in (("time", "answer_time"), ("shift", "answer_shift"), ("angle", "answer_angle"), ("zone", "answer_zone")): if tk in combined[k]: got_s = _fmt_time_short(combined[k][tk]["got"]) mk = "O" if combined[k][tk]["correct"] else "X" parts.append(f"{short}={got_s}({mk})") if "answer_hands" in combined[k]: e = combined[k]["answer_hands"] parts.append(f"hands={json.dumps(e['got'])}({'O' if e['correct'] else 'X'})") lines.append(f"{img_name} ({gt_time}): {' | '.join(parts)}") summary_path.parent.mkdir(parents=True, exist_ok=True) summary_path.write_text("\n".join(lines) + ("\n" if lines else ""), encoding="utf-8") print("\n=== Final ClockBench Scores ===") print(json.dumps(scores, ensure_ascii=False, indent=2)) print(f"\n[완료] 채점 결과 저장: {output_path}") if summary_path is not None: print(f"[완료] 요약 텍스트 저장: {summary_path}") return combined def main() -> None: parser = argparse.ArgumentParser(description="ClockBench 공식 채점 스크립트") parser.add_argument("--answers", type=Path, default=Path("input/answers.json"), help="정답 JSON 경로") parser.add_argument("--predictions", type=Path, default=Path("output/predictions.json"), help="모델 예측 JSON 경로") parser.add_argument("--output", type=Path, default=Path("output/grading.json"), help="채점 결과 저장 경로") parser.add_argument("--summary-output", type=Path, default=Path("output/results_summary.txt"), help="요약 텍스트 저장 경로 ('시계(시간): 모델이 말한 답' 형식)") args = parser.parse_args() grade(args.answers, args.predictions, args.output, summary_path=args.summary_output) if __name__ == "__main__": main()