File size: 5,510 Bytes
3127b61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# 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()