LiZZieeee's picture
Upload HighlightBench files 1-20
2d67c36 verified
Raw
History Blame Contribute Delete
6.26 kB
from __future__ import annotations
import argparse
import json
import re
from collections import Counter, defaultdict
from decimal import Decimal, InvalidOperation
from pathlib import Path
from typing import Any
ARROWS = "↑↓▲▼△▽↗↘⇧⇩↟↡"
NUM_RE = re.compile(r"^[+-]?\d+(\.\d+)?$")
WS_RE = re.compile(r"\s+")
SHADE_PREFIXES = {"light", "dark", "medium", "pale", "deep", "bright"}
BASE_COLORS = {
"blue",
"green",
"purple",
"pink",
"red",
"orange",
"yellow",
"gray",
"grey",
}
def strip_arrows(s: str) -> str:
return "".join(ch for ch in s if ch not in ARROWS)
def normalize_value(x: Any) -> Any:
if x is None:
return None
if isinstance(x, bool):
return x
if isinstance(x, (int, float)):
return normalize_number(str(x))
if isinstance(x, str):
s = strip_arrows(x.strip())
while len(s) >= 2 and (s[0], s[-1]) in [("(", ")"), ("[", "]"), ("{", "}"), ("<", ">")]:
s = s[1:-1].strip()
s = s.strip(" ,;")
s = s.replace("−", "-").replace("—", "-").replace("–", "-")
s = re.sub(r"\s*±\s*", "±", s)
s = re.sub(r"\s*\+\s*/\s*-\s*", "±", s)
s = re.sub(r"\s*\+\s*-\s*", "±", s)
s = re.sub(r"\s*%\s*", "%", s)
s = WS_RE.sub(" ", s).strip()
s = normalize_color_name(s)
# Optional: uncomment to ignore citation suffixes, e.g. "Foggy Zurich [52]".
# s = re.sub(r"\s*\[\d+\]", "", s).strip()
if NUM_RE.match(s):
return normalize_number(s)
return s
return x
def normalize_color_name(s: str) -> str:
color = s.lower().replace("-", "_").replace(" ", "_")
parts = [p for p in color.split("_") if p]
if len(parts) >= 2 and parts[0] in SHADE_PREFIXES and parts[-1] in BASE_COLORS:
return "gray" if parts[-1] == "grey" else parts[-1]
if color in BASE_COLORS:
return "gray" if color == "grey" else color
return s
def normalize_number(s: str) -> str:
try:
d = Decimal(s)
except InvalidOperation:
return s.strip()
if d == 0:
return "0"
out = format(d.normalize(), "f")
return out.rstrip("0").rstrip(".") if "." in out else out
def parse_answer(ans: Any) -> Any:
if not isinstance(ans, str):
return ans
text = ans.strip()
for _ in range(3):
if text.startswith("[") or text.startswith("{") or (text.startswith('"') and text.endswith('"')):
try:
parsed = json.loads(text)
except Exception:
break
if isinstance(parsed, str):
text = parsed.strip()
continue
return parsed
break
return ans
def normalize_record(x: dict[str, Any]) -> str:
return json.dumps({k: normalize_value(v) for k, v in x.items()}, ensure_ascii=False, sort_keys=True)
def multiset_score(gt_items: list[Any], pr_items: list[Any]) -> tuple[float, bool, int, int, int]:
gt = Counter(gt_items)
pr = Counter(pr_items)
keys = gt.keys() | pr.keys()
tp = sum(min(gt[k], pr[k]) for k in keys)
fp = sum(max(pr[k] - gt[k], 0) for k in keys)
fn = sum(max(gt[k] - pr[k], 0) for k in keys)
exact = fp == 0 and fn == 0
score = 1.0 if exact else (2 * tp / (2 * tp + fp + fn) if (2 * tp + fp + fn) else 1.0)
return score, exact, tp, fp, fn
def score_answer(gt: Any, pred: Any) -> dict[str, Any]:
pred = parse_answer(pred)
if isinstance(gt, dict):
exact = normalize_record(gt) == normalize_record(pred) if isinstance(pred, dict) else False
return {"score": 1.0 if exact else 0.0, "exact": exact}
if isinstance(gt, list):
if all(isinstance(x, dict) for x in gt):
gt_items = [normalize_record(x) for x in gt]
pr_list = pred if isinstance(pred, list) else ([pred] if isinstance(pred, dict) else [])
pr_items = [normalize_record(x) for x in pr_list if isinstance(x, dict)]
else:
gt_items = [normalize_value(x) for x in gt]
pr_list = pred if isinstance(pred, list) else [pred]
pr_items = [normalize_value(x) for x in pr_list]
score, exact, tp, fp, fn = multiset_score(gt_items, pr_items)
return {"score": score, "exact": exact, "tp": tp, "fp": fp, "fn": fn}
exact = normalize_value(gt) == normalize_value(pred)
return {"score": 1.0 if exact else 0.0, "exact": exact}
def load_jsonl(path: Path) -> list[dict[str, Any]]:
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
def main() -> int:
parser = argparse.ArgumentParser(description="Score compact HighlightBench QA predictions.")
parser.add_argument("--gt", required=True)
parser.add_argument("--pred", required=True)
parser.add_argument("--out", default=None)
args = parser.parse_args()
gt_rows = load_jsonl(Path(args.gt))
pred_rows = load_jsonl(Path(args.pred))
pred_by_qid = {r.get("qid"): r for r in pred_rows}
scores = []
exacts = []
per_item = []
by_split = defaultdict(list)
for gt in gt_rows:
qid = gt.get("qid")
pred = pred_by_qid.get(qid, {})
res = score_answer(gt.get("answer"), pred.get("answer"))
scores.append(float(res["score"]))
exacts.append(bool(res["exact"]))
split = gt.get("dataset", "unknown")
by_split[split].append(float(res["score"]))
per_item.append({"qid": qid, "score": res["score"], "exact": res["exact"]})
summary = {
"num_items": len(gt_rows),
"overall_mean": sum(scores) / len(scores) if scores else 0.0,
"overall_exact_rate": sum(exacts) / len(exacts) if exacts else 0.0,
"per_split_mean": {k: sum(v) / len(v) for k, v in by_split.items()},
"missing_predictions": sum(1 for r in gt_rows if r.get("qid") not in pred_by_qid),
}
out = {"summary": summary, "per_item": per_item}
out_path = Path(args.out) if args.out else Path(args.pred).with_suffix(".score.json")
out_path.write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(out_path)
return 0
if __name__ == "__main__":
raise SystemExit(main())