File size: 14,423 Bytes
57c7939
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
#!/usr/bin/env python3
"""Rubric scoring for the AudioSpan release.

Calls a judge model (via the OpenAI chat-completions API) to score each
criterion on semantic + temporal dimensions, then aggregates with
importance weights. Depends only on `openai` and `tenacity`.

The answer file carries only what the model produced, one record per
question: {"qa_id": ..., "answer": "..."}. Questions and criteria are
joined in from metadata/rubric/{S,M,L}.jsonl; questions with no answer
score zero.

Usage:
    python score_rubric.py --input results/<model>/rubric.jsonl \
                           --judges gpt-5.4-2026-03-05 [--rounds 1]
"""

import argparse
import json
import logging
import os
import re
import sys
from pathlib import Path

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)

IMPORTANCE_WEIGHT = {"essential": 1.0, "supporting": 0.5}
VALID_SEMANTIC = {"correct", "partial", "wrong", "none"}
VALID_TEMPORAL = {"correct", "wrong", "missing", "none"}

SCRIPT_DIR = Path(__file__).resolve().parent
DEFAULT_JUDGE_PROMPT = SCRIPT_DIR / "judge_criteria.md"
DEFAULT_JUDGES = ["gpt-5.4-2026-03-05"]
DEFAULT_ROUNDS = 1

# (prefix, base_url, api_key_env_var). Order matters: first match wins.
DEFAULT_API_BASEES: list[tuple[str, str, str]] = [
    ("qwen",    "https://dashscope.aliyuncs.com/compatible-mode/v1",        "DASHSCOPE_API_KEY"),
    ("gpt",     "https://api.openai.com/v1",                                "OPENAI_API_KEY"),
    ("o1",      "https://api.openai.com/v1",                                "OPENAI_API_KEY"),
    ("o3",      "https://api.openai.com/v1",                                "OPENAI_API_KEY"),
    ("o4",      "https://api.openai.com/v1",                                "OPENAI_API_KEY"),
    ("gemini",  "https://generativelanguage.googleapis.com/v1beta/openai/", "GEMINI_API_KEY"),
    ("doubao",  "https://ark.cn-beijing.volces.com/api/v3",                 "ARK_API_KEY"),
    ("seed",    "https://ark.cn-beijing.volces.com/api/v3",                 "ARK_API_KEY"),
    ("deepseek","https://api.deepseek.com/v1",                              "DEEPSEEK_API_KEY"),
]


def _resolve_default_api_base(model: str) -> tuple[str, str]:
    m = model.lower()
    for prefix, base, env in DEFAULT_API_BASEES:
        if m == prefix or m.startswith(prefix):
            nxt = m[len(prefix):len(prefix) + 1]
            if nxt == "" or not nxt.isalpha():
                return base, env
    return "https://api.openai.com/v1", "OPENAI_API_KEY"


RELEASE_ROOT = Path(__file__).resolve().parent.parent
TIERS = ("S", "M", "L")


def load_records(input_path: str, data_root: Path) -> list[dict]:
    """Join answer records with rubric metadata by qa_id."""
    preds: dict[str, str] = {}
    with open(input_path, encoding="utf-8", errors="replace") as fh:
        for lineno, line in enumerate(fh, 1):
            line = line.strip()
            if not line:
                continue
            try:
                rec = json.loads(line)
            except json.JSONDecodeError as e:
                logger.warning("Skipping bad line %d: %s", lineno, e)
                continue
            if rec.get("qa_id"):
                preds[rec["qa_id"]] = rec.get("answer")
    if not preds:
        sys.exit(f"ERROR: no valid answers in {input_path}")

    records = []
    for tier in TIERS:
        path = data_root / "metadata" / "rubric" / f"{tier}.jsonl"
        if not path.is_file():
            sys.exit(f"ERROR: metadata not found: {path}")
        with open(path, encoding="utf-8") as fh:
            for line in fh:
                if not line.strip():
                    continue
                q = json.loads(line)
                q["model_response"] = preds.get(q["qa_id"])
                records.append(q)

    unknown = sorted(set(preds) - {r["qa_id"] for r in records})
    if unknown:
        logger.warning("Ignoring %d unknown qa_id(s), e.g. %s", len(unknown), unknown[0])
    covered = sum(1 for r in records if r["model_response"] is not None)
    logger.info("Answers cover %d/%d questions (missing score zero)", covered, len(records))
    return records


def format_criteria(criteria: list[dict]) -> str:
    lines = []
    for i, c in enumerate(criteria):
        tr = c.get("time_range")
        tr_str = f" [{tr[0]}-{tr[1]}]" if tr and len(tr) == 2 else ""
        lines.append(f"{i+1}. [{c.get('importance', 'essential')}]{tr_str} {c['text']}")
    return "\n".join(lines)


_SEM_SCORE = {"correct": 1.0, "partial": 0.5, "wrong": 0.0}


def _criterion_score(semantic: str, temporal: str, has_time_range: bool) -> float:
    sem = _SEM_SCORE.get(semantic, 0.0)
    if has_time_range:
        if semantic == "wrong":
            return 0.0
        if temporal in ("none", "missing"):
            return sem
        return (sem + (1.0 if temporal == "correct" else 0.0)) / 2
    if temporal in ("correct", "wrong"):
        return 1.0 if temporal == "correct" else 0.0
    return sem


def _rubric_score(judged: list[dict], ref_criteria: list[dict]) -> float:
    judged_by_idx = {jc.get("index", i): jc for i, jc in enumerate(judged)}
    weighted_sum, weight_total = 0.0, 0.0
    for ref_idx, ref in enumerate(ref_criteria):
        jc = judged_by_idx.get(ref_idx)
        if not jc:
            continue
        has_tr = ref.get("importance", "essential") != "essential" and ref.get("time_range") is not None
        w = IMPORTANCE_WEIGHT.get(ref.get("importance", "essential"), 1.0)
        weighted_sum += w * _criterion_score(jc.get("semantic", "wrong"), jc.get("temporal", "none"), has_tr)
        weight_total += w
    return round(weighted_sum / weight_total if weight_total else 0.0, 4)


def _trimmed_mean(scores: list[float]) -> float:
    s = sorted(scores)[1:-1] if len(scores) >= 3 else list(scores)
    return sum(s) / len(s) if s else 0.0


def _extract_json(text: str) -> dict | None:
    stripped = text.strip()
    fence = re.search(r"```(?:json)?\s*\n(.*?)\n\s*```", stripped, re.DOTALL)
    if fence:
        stripped = fence.group(1).strip()
    try:
        return json.loads(stripped)
    except json.JSONDecodeError:
        first, last = stripped.find("{"), stripped.rfind("}")
        if first != -1 and last > first:
            try:
                return json.loads(stripped[first:last + 1])
            except json.JSONDecodeError:
                return None
    return None


def _load_completed(evals_path: str) -> set[tuple[str, str, int]]:
    done: set[tuple[str, str, int]] = set()
    if not os.path.isfile(evals_path):
        return done
    with open(evals_path, encoding="utf-8", errors="replace") as fh:
        for line in fh:
            line = line.strip()
            if not line:
                continue
            try:
                ev = json.loads(line)
                done.add((ev.get("qa_id"), ev["judge"], ev["round"]))
            except (json.JSONDecodeError, KeyError):
                continue
    return done


def run_rubric(records: list[dict], judges: list[str], rounds: int,
               evals_path: str, judge_prompt_path: str,
               api_base: str, api_key: str) -> dict:
    from openai import OpenAI
    from tenacity import retry, stop_after_attempt, wait_exponential_jitter

    system_prompt = Path(judge_prompt_path).read_text(encoding="utf-8")
    client = OpenAI(api_key=api_key, base_url=api_base)

    done = _load_completed(evals_path)
    pending = [
        (rec, judge, r)
        for rec in records
        if rec.get("criteria")
        for judge in judges
        for r in range(rounds)
        if (rec["qa_id"], judge, r) not in done
    ]
    logger.info("Rubric: %d pending / %d total evals", len(pending),
                len(records) * len(judges) * rounds)

    write_mode = "a" if done else "w"
    fh = open(evals_path, write_mode, encoding="utf-8")
    completed = 0

    @retry(wait=wait_exponential_jitter(initial=3, max=15, exp_base=2, jitter=2),
           stop=stop_after_attempt(3))
    def _call_judge(judge: str, user_msg: str) -> str:
        resp = client.chat.completions.create(
            model=judge,
            messages=[{"role": "system", "content": system_prompt},
                      {"role": "user", "content": user_msg}],
            max_tokens=3000, temperature=0.0,
            response_format={"type": "json_object"},
        )
        return resp.choices[0].message.content or ""

    try:
        for rec, judge, round_idx in pending:
            user_msg = (
                f"## Question\n\n{rec['question']}\n\n"
                f"## Evaluation Criteria\n\n{format_criteria(rec['criteria'])}\n\n"
                f"## Model Response\n\n{rec.get('model_response') or ''}"
            )
            judged = None
            for _ in range(3):
                try:
                    raw = _call_judge(judge, user_msg)
                    result = _extract_json(raw) or {}
                    judged = result.get("criteria", [])
                    for j in judged:
                        if j.get("temporal") == "partial":
                            j["temporal"] = "correct"
                    if len(judged) != len(rec["criteria"]):
                        judged = None
                        continue
                    if any(j.get("semantic") not in VALID_SEMANTIC
                           or j.get("temporal") not in VALID_TEMPORAL
                           for j in judged):
                        judged = None
                        continue
                    break
                except Exception as e:
                    logger.warning("Judge %s id=%s: %s", judge, rec["qa_id"], str(e)[:120])
                    judged = None
            if not judged:
                logger.warning("Judge %s id=%s: all attempts failed", judge, rec["qa_id"])
                continue
            score = _rubric_score(judged, rec["criteria"])
            ev = {
                "qa_id": rec["qa_id"], "judge": judge, "round": round_idx, "score": score,
                "criteria": [
                    {"index": j.get("index", j_idx),
                     "importance": rec["criteria"][j_idx].get("importance", "essential"),
                     "semantic": j.get("semantic"), "temporal": j.get("temporal"),
                     "score": _criterion_score(
                         j.get("semantic"), j.get("temporal"),
                         rec["criteria"][j_idx].get("importance", "essential") != "essential"
                         and rec["criteria"][j_idx].get("time_range") is not None,
                     )}
                    for j_idx, j in enumerate(judged)
                ],
            }
            fh.write(json.dumps(ev, ensure_ascii=False) + "\n")
            fh.flush()
            completed += 1
            if completed % 50 == 0:
                logger.info("Rubric progress: %d/%d", completed, len(pending))
    finally:
        fh.close()

    return _aggregate(evals_path, records, judges)


def _aggregate(evals_path: str, records: list[dict], judges: list[str]) -> dict:
    evals_by_id: dict[str, list[dict]] = {}
    with open(evals_path, encoding="utf-8", errors="replace") as fh:
        for line in fh:
            line = line.strip()
            if not line:
                continue
            try:
                ev = json.loads(line)
            except json.JSONDecodeError:
                continue
            evals_by_id.setdefault(ev.get("qa_id"), []).append(ev)

    scored = []
    for rec in records:
        evals = [e for e in evals_by_id.get(rec["qa_id"], [])
                 if e.get("judge") == judges[0]]
        score = round(_trimmed_mean([e["score"] for e in evals]) * 100, 2) if evals else 0
        scored.append({"qa_id": rec["qa_id"], "score": score})

    total = len(scored)
    mean = sum(s["score"] for s in scored) / total if total else 0
    return {"mode": "rubric", "total": total,
            "avg_score": round(mean, 2), "scored_records": scored}


def main():
    parser = argparse.ArgumentParser(description="Rubric-score AudioSpan model outputs")
    parser.add_argument("--input", required=True,
                        help="Prediction JSONL: {\"qa_id\": ..., \"answer\": \"...\"} per line")
    parser.add_argument("--output", help="Aggregated scored JSONL (default: <input>_scored.jsonl)")
    parser.add_argument("--evals", help="Per-eval JSONL (default: <input>_evals.jsonl)")
    parser.add_argument("--data-root", type=Path, default=RELEASE_ROOT,
                        help="release root holding metadata/ (default: parent of evaluate/)")
    parser.add_argument("--judges", help="Comma-separated judge models")
    parser.add_argument("--rounds", type=int, default=DEFAULT_ROUNDS)
    parser.add_argument("--judge-prompt", default=str(DEFAULT_JUDGE_PROMPT))
    parser.add_argument("--api-base",
                        help="OpenAI-compatible base URL (default: inferred from first judge)")
    parser.add_argument("--api-key",
                        help="API key (default: provider env var, see module docstring)")
    args = parser.parse_args()

    records = load_records(args.input, args.data_root.resolve())

    judges = args.judges.split(",") if args.judges else DEFAULT_JUDGES
    default_base, default_env = _resolve_default_api_base(judges[0])
    if not args.api_base:
        args.api_base = default_base
        logger.info("Resolved --api-base from judge %r: %s", judges[0], args.api_base)
    if not args.api_key:
        args.api_key = os.environ.get(default_env) or os.environ.get("OPENAI_API_KEY")
    if not args.api_key:
        parser.error(f"--api-key or {default_env} required for judge {judges[0]!r}")

    evals_path = args.evals or args.input.replace(".jsonl", "_evals.jsonl")
    summary = run_rubric(
        records, judges, args.rounds, evals_path,
        judge_prompt_path=args.judge_prompt,
        api_base=args.api_base, api_key=args.api_key,
    )

    out_path = args.output or args.input.replace(".jsonl", "_scored.jsonl")
    with open(out_path, "w", encoding="utf-8") as fh:
        for s in summary.get("scored_records", []):
            fh.write(json.dumps(s, ensure_ascii=False) + "\n")
    logger.info("Scored records: %s", out_path)

    print(json.dumps({k: v for k, v in summary.items() if k != "scored_records"},
                     indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()