PolyText-Bench / summarize.py
SujieHu's picture
Upload folder using huggingface_hub
3127b61 verified
Raw History Blame Contribute Delete
5.51 kB
# Copyright 2026 Jayce-Ping
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations.
"""Validate complete PolyText-Bench scores and write aggregate metrics."""
import argparse
import json
import math
from pathlib import Path
from typing import Any, Dict, List
DEFAULT_PROMPTS = Path(__file__).resolve().parent
def read_jsonl(path: Path) -> List[Dict[str, Any]]:
"""Read nonempty JSONL objects."""
rows = [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
if any(not isinstance(row, dict) for row in rows):
raise TypeError(f"Expected JSON objects in {path}")
return rows
def checked_score(value: float) -> float:
"""Return a finite normalized score."""
score = float(value)
if not math.isfinite(score) or not 0 <= score <= 1:
raise ValueError(f"Expected a normalized score, got {score}")
return score
def expected_keys(prompts: Path, mode: str, repeats: int) -> List[str]:
"""Return all expected image keys for one language."""
language = mode.lower()
rows = []
for task in ("critical", "optional"):
path = prompts / f"{task}_{language}.jsonl"
if not path.is_file():
raise FileNotFoundError(f"Missing benchmark split: {path}")
rows.extend(read_jsonl(path))
keys = [
f"{row['pair_id']}_{row['task_type']}_{repeat}"
for row in rows
for repeat in range(1, repeats + 1)
]
if len(keys) != len(set(keys)):
raise ValueError(f"Benchmark contains duplicate keys for mode={mode}")
return keys
def summarize(records: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Average images equally and exclude undefined optional glyph scores."""
critical = [record for record in records if record["task_type"] == "critical"]
optional = [record for record in records if record["task_type"] == "optional"]
optional_valid = [record for record in optional if record["OG_valid"]]
return dict(
CS=sum(checked_score(record["CS"]) for record in critical) / len(critical),
CG=sum(checked_score(record["CG"]) for record in critical) / len(critical),
CG_valid=f"{sum(record['CG_valid'] for record in critical)}/{len(critical)}",
OG=(
sum(checked_score(record["OG"]) for record in optional_valid) / len(optional_valid)
if optional_valid
else None
),
OG_valid=f"{len(optional_valid)}/{len(optional)}",
)
def markdown(language: str, metrics: Dict[str, Any]) -> str:
"""Render one language row as Markdown."""
values = [
(
"N/A"
if metrics[key] is None
else (
f"{metrics[key]:.3f}"
if isinstance(metrics[key], (float, int))
else str(metrics[key])
)
)
for key in ("CS", "CG", "CG_valid", "OG", "OG_valid")
]
return "\n".join(
[
"| Language | CS ↑ | CG ↑ | CG valid | OG ↑ | OG valid |",
"|---|---:|---:|---|---:|---|",
"| " + " | ".join([language] + values) + " |",
"",
]
)
def main() -> None:
"""Validate records and export JSON and Markdown summaries."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--prompts", type=Path, default=DEFAULT_PROMPTS)
parser.add_argument("--scores-dir", type=Path, required=True)
parser.add_argument("--mode", choices=["EN", "ZH"], required=True)
parser.add_argument("--repeats", type=int, default=4)
args = parser.parse_args()
if args.repeats < 1:
parser.error("repeats must be positive")
score_path = args.scores_dir / "eval_results.jsonl"
if not score_path.is_file():
raise FileNotFoundError(f"Missing score file: {score_path}")
records = read_jsonl(score_path)
keys = [record.get("key") for record in records]
expected = expected_keys(args.prompts, args.mode, args.repeats)
if len(keys) != len(set(keys)):
raise ValueError("Score file contains duplicate image keys")
if set(keys) != set(expected):
missing = sorted(set(expected) - set(keys))
unexpected = sorted(set(keys) - set(expected))
raise ValueError(
f"Incomplete scores: expected {len(expected)}, got {len(keys)}; "
f"missing={missing[:5]}, unexpected={unexpected[:5]}"
)
by_key = {record["key"]: record for record in records}
ordered = [by_key[key] for key in expected]
metrics = summarize(ordered)
result = dict(
complete=True,
language=args.mode.lower(),
images=len(ordered),
score_scale="0-1",
metrics=metrics,
)
args.scores_dir.mkdir(parents=True, exist_ok=True)
(args.scores_dir / "summary.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2, allow_nan=False) + "\n"
)
report = markdown(args.mode.lower(), metrics)
(args.scores_dir / "scores.md").write_text(report)
print(report, end="")
if __name__ == "__main__":
main()