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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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#!/usr/bin/env python3
"""Model-agnostic inference and scoring entry point for DOVE.

The public model interface is a JSONL file with at least ``qid`` and
``caption``.  ``infer`` is an optional convenience layer for Python adapters;
``judge`` and ``score`` work with predictions produced by any framework.
"""

from __future__ import annotations

import argparse
import importlib.util
import json
import re
import threading
import time
from collections import Counter, defaultdict
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any, Callable


ROOT = Path(__file__).resolve().parents[1]
DEFAULT_QUESTIONS = ROOT / "data/public/questions.jsonl"
DEFAULT_PROBES = ROOT / "data/private/temporal_probes.jsonl"

JUDGE_SYSTEM = """You are a strict caption-evidence checker. Use only the candidate caption.
Do not answer from common sense or outside knowledge. If the caption explicitly supports exactly
one choice, return state=answered and its zero-based index. If it lacks the required temporal
information, return state=not_mentioned. If it supports multiple incompatible choices or is truly
unclear, return state=ambiguous. Return JSON only."""


def read_jsonl(path: Path) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    with path.open(encoding="utf-8") as handle:
        for number, line in enumerate(handle, 1):
            if not line.strip():
                continue
            try:
                value = json.loads(line)
            except json.JSONDecodeError as exc:
                raise ValueError(f"{path}:{number}: invalid JSON: {exc}") from exc
            if not isinstance(value, dict):
                raise ValueError(f"{path}:{number}: expected a JSON object")
            rows.append(value)
    return rows


def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    temporary = path.with_suffix(path.suffix + ".tmp")
    with temporary.open("w", encoding="utf-8") as handle:
        for row in rows:
            handle.write(json.dumps(row, ensure_ascii=False, sort_keys=True) + "\n")
    temporary.replace(path)


def unique_by(rows: list[dict[str, Any]], field: str, source: Path) -> dict[str, dict[str, Any]]:
    values: dict[str, dict[str, Any]] = {}
    duplicates: list[str] = []
    for row in rows:
        key = str(row.get(field, ""))
        if not key:
            raise ValueError(f"{source}: row missing {field!r}")
        if key in values:
            duplicates.append(key)
        values[key] = row
    if duplicates:
        raise ValueError(f"{source}: duplicate {field}s: {duplicates[:5]}")
    return values


def parse_object(value: str) -> dict[str, Any]:
    parsed = json.loads(value)
    if not isinstance(parsed, dict):
        raise argparse.ArgumentTypeError("--model-args must be a JSON object")
    return parsed


def resolve_question_video(row: dict[str, Any]) -> dict[str, Any]:
    result = dict(row)
    path = Path(str(result["video"]))
    result["video"] = str(path if path.is_absolute() else ROOT / path)
    return result


def validate_release(questions_path: Path, probes_path: Path, check_videos: bool) -> dict[str, Any]:
    questions = read_jsonl(questions_path)
    probes = read_jsonl(probes_path)
    qmap = unique_by(questions, "qid", questions_path)
    pmap = unique_by(probes, "probe_id", probes_path)
    unknown = sorted({str(row.get("qid")) for row in probes} - set(qmap))
    if unknown:
        raise ValueError(f"private probes reference {len(unknown)} unknown qids")
    protocols = Counter(str(row.get("input_protocol")) for row in questions)
    axes = Counter(str(row.get("axis")) for row in probes)
    missing_videos: list[str] = []
    if check_videos:
        for row in questions:
            path = Path(resolve_question_video(row)["video"])
            if not path.is_file():
                missing_videos.append(str(path))
    if missing_videos:
        raise FileNotFoundError(f"missing {len(missing_videos)} videos; first={missing_videos[0]}")
    return {
        "questions": len(questions),
        "groups": len({int(row["gid"]) for row in questions}),
        "unique_videos": len({str(row["video"]) for row in questions}),
        "probes": len(pmap),
        "scored_clips": len({str(row["qid"]) for row in probes}),
        "unscored_qids": sorted(set(qmap) - {str(row["qid"]) for row in probes}),
        "protocols": dict(protocols),
        "axes": dict(axes),
        "videos_checked": check_videos,
    }


def load_adapter(path: Path, model_args: dict[str, Any]) -> Callable[[dict[str, Any]], str]:
    spec = importlib.util.spec_from_file_location("dove_user_adapter", path)
    if spec is None or spec.loader is None:
        raise ValueError(f"cannot load adapter: {path}")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    factory = getattr(module, "create_predictor", None)
    if not callable(factory):
        raise ValueError(f"{path} must define create_predictor(model_args)")
    predictor = factory(model_args)
    if not callable(predictor):
        raise ValueError("create_predictor must return a callable")
    return predictor


def infer(args: argparse.Namespace) -> None:
    questions = read_jsonl(args.questions)
    if args.num_shards < 1 or not 0 <= args.shard_id < args.num_shards:
        raise ValueError("require num_shards >= 1 and 0 <= shard_id < num_shards")
    questions = questions[args.shard_id :: args.num_shards]
    if args.limit > 0:
        questions = questions[: args.limit]
    existing: dict[str, dict[str, Any]] = {}
    if args.output.exists():
        existing = unique_by(read_jsonl(args.output), "qid", args.output)
    work = [row for row in questions if str(row["qid"]) not in existing]
    print(f"assigned={len(questions)} done={len(questions)-len(work)} remaining={len(work)}")
    if not work:
        return
    predictor = load_adapter(args.adapter, args.model_args)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open("a", encoding="utf-8") as handle:
        for index, row in enumerate(work, 1):
            request = resolve_question_video(row)
            video = Path(request["video"])
            if not video.is_file():
                raise FileNotFoundError(video)
            caption = predictor(request)
            if not isinstance(caption, str):
                raise TypeError(f"adapter returned {type(caption).__name__}, expected str")
            output = {
                "qid": row["qid"],
                "gid": row["gid"],
                "seg_index": row["seg_index"],
                "input_protocol": row["input_protocol"],
                "caption": caption.strip(),
                "model": args.model_name,
            }
            handle.write(json.dumps(output, ensure_ascii=False, sort_keys=True) + "\n")
            handle.flush()
            if index % 10 == 0 or index == len(work):
                print(f"completed={index}/{len(work)}", flush=True)


def validate_predictions(questions_path: Path, predictions_path: Path, allow_partial: bool = False) -> dict[str, dict[str, Any]]:
    questions = unique_by(read_jsonl(questions_path), "qid", questions_path)
    predictions = unique_by(read_jsonl(predictions_path), "qid", predictions_path)
    extra = sorted(set(predictions) - set(questions))
    missing = sorted(set(questions) - set(predictions))
    if extra:
        raise ValueError(f"predictions contain {len(extra)} unknown qids; first={extra[0]}")
    if missing and not allow_partial:
        raise ValueError(f"predictions are missing {len(missing)} qids; first={missing[0]}")
    for qid, row in predictions.items():
        if not isinstance(row.get("caption"), str):
            raise ValueError(f"prediction {qid}: caption must be a string")
        protocol = row.get("input_protocol")
        if protocol is not None and protocol != questions[qid].get("input_protocol"):
            raise ValueError(f"prediction {qid}: input_protocol mismatch")
    return predictions


def parse_json_object(text: str) -> dict[str, Any]:
    fenced = re.search(r"```(?:json)?\s*(.*?)```", text, re.S)
    if fenced:
        text = fenced.group(1)
    start = text.find("{")
    if start < 0:
        raise ValueError("response contains no JSON object")
    depth = 0
    in_string = False
    escaped = False
    for index, char in enumerate(text[start:], start):
        if in_string:
            if escaped:
                escaped = False
            elif char == "\\":
                escaped = True
            elif char == '"':
                in_string = False
        elif char == '"':
            in_string = True
        elif char == "{":
            depth += 1
        elif char == "}":
            depth -= 1
            if depth == 0:
                return json.loads(text[start : index + 1])
    raise ValueError("unterminated JSON object")


def judge(args: argparse.Namespace) -> None:
    try:
        from openai import OpenAI
    except ImportError as exc:
        raise RuntimeError("judge requires `pip install openai`") from exc

    predictions = validate_predictions(args.questions, args.predictions)
    probes = read_jsonl(args.probes)
    unique_by(probes, "probe_id", args.probes)
    completed: dict[str, dict[str, Any]] = {}
    if args.output.exists():
        completed = {
            str(row["probe_id"]): row
            for row in read_jsonl(args.output)
            if row.get("ok") and row.get("probe_id")
        }
    work = [row for row in probes if str(row["probe_id"]) not in completed]
    print(f"probes={len(probes)} done={len(completed)} remaining={len(work)}")
    local = threading.local()

    def client() -> Any:
        if not hasattr(local, "client"):
            local.client = OpenAI(base_url=args.base_url, api_key=args.api_key, timeout=args.timeout)
        return local.client

    def judge_one(probe: dict[str, Any]) -> dict[str, Any]:
        caption = predictions[str(probe["qid"])]["caption"].strip()
        if not caption:
            return {
                "probe_id": probe["probe_id"],
                "state": "not_mentioned",
                "selected_index": None,
                "ok": True,
                "backend": "empty-caption-zero-score",
            }
        choices = "\n".join(f"{i}. {value}" for i, value in enumerate(probe["choices"]))
        request = (
            f"CANDIDATE CAPTION:\n{caption}\n\nQUESTION:\n{probe['question']}\n\n"
            f"CHOICES:\n{choices}\n\n"
            'Return exactly {"state":"answered|not_mentioned|ambiguous","selected_index":0}. '
            "For not_mentioned or ambiguous, selected_index must be null."
        )
        error = ""
        for attempt in range(args.retries):
            try:
                response = client().chat.completions.create(
                    model=args.judge_model,
                    temperature=0,
                    max_tokens=96,
                    messages=[
                        {"role": "system", "content": JUDGE_SYSTEM},
                        {"role": "user", "content": request},
                    ],
                )
                value = parse_json_object(response.choices[0].message.content or "")
                state = value.get("state")
                selected = value.get("selected_index")
                if state not in {"answered", "not_mentioned", "ambiguous"}:
                    raise ValueError(f"invalid state: {state!r}")
                if state == "answered" and selected not in range(4):
                    state, selected = "ambiguous", None
                if state != "answered":
                    selected = None
                return {
                    "probe_id": probe["probe_id"],
                    "state": state,
                    "selected_index": selected,
                    "ok": True,
                    "backend": args.judge_model,
                }
            except Exception as exc:  # noqa: BLE001
                error = f"{type(exc).__name__}: {exc}"[:500]
                time.sleep(1.5 * (attempt + 1))
        return {"probe_id": probe["probe_id"], "ok": False, "error": error}

    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open("a", encoding="utf-8") as handle, ThreadPoolExecutor(max_workers=args.workers) as pool:
        for index, result in enumerate(pool.map(judge_one, work), 1):
            handle.write(json.dumps(result, ensure_ascii=False, sort_keys=True) + "\n")
            handle.flush()
            if index % 50 == 0 or index == len(work):
                print(f"completed={index}/{len(work)}", flush=True)
    latest = {
        str(row["probe_id"]): row
        for row in read_jsonl(args.output)
        if row.get("probe_id")
    }
    incomplete = [
        probe["probe_id"]
        for probe in probes
        if not latest.get(str(probe["probe_id"]), {}).get("ok")
    ]
    if incomplete:
        raise RuntimeError(
            f"judging incomplete: {len(incomplete)} failed/missing probes; rerun to retry"
        )


def mean(values: list[float]) -> float:
    return sum(values) / len(values) if values else 0.0


def score(args: argparse.Namespace) -> dict[str, Any]:
    probes = unique_by(read_jsonl(args.probes), "probe_id", args.probes)
    # The judge is append-only. A successful retry intentionally follows an
    # older failed row with the same probe_id, so consume the latest attempt.
    latest_judgments = {
        str(row["probe_id"]): row
        for row in read_jsonl(args.judgments)
        if row.get("probe_id")
    }
    judgments = {
        key: value
        for key, value in latest_judgments.items()
        if value.get("ok", True) and key in probes
    }
    missing = sorted(set(probes) - set(judgments))
    if missing:
        raise ValueError(f"incomplete judgments: missing {len(missing)}; first={missing[0]}")
    per_axis: dict[str, list[float]] = defaultdict(list)
    per_clip: dict[str, list[float]] = defaultdict(list)
    wrong = absent = 0
    for probe_id, probe in probes.items():
        judgment = judgments[probe_id]
        state = judgment.get("state")
        selected = judgment.get("selected_index")
        correct = float(state == "answered" and selected == probe["answer_index"])
        wrong += int(state == "answered" and selected != probe["answer_index"])
        absent += int(state in {"not_mentioned", "ambiguous"})
        per_axis[str(probe["axis"])].append(correct)
        per_clip[str(probe["qid"])].append(correct)
    axis_scores = {axis: mean(per_axis[axis]) for axis in ("order", "state", "outcome")}
    all_values = [value for values in per_axis.values() for value in values]
    report = {
        "schema_version": "dove-v2-score-v1",
        "probes": len(probes),
        "clips": len(per_clip),
        "groups": len({int(row["gid"]) for row in probes.values()}),
        "temp_cov": mean(all_values),
        "tec": mean(list(axis_scores.values())),
        "clip_complete": mean([float(all(values)) for values in per_clip.values()]),
        "by_axis": {
            axis: {"count": len(per_axis[axis]), "temp_cov": axis_scores[axis]}
            for axis in ("order", "state", "outcome")
        },
        "contradiction_rate": wrong / len(probes),
        "not_mentioned_rate": absent / len(probes),
    }
    text = json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n"
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(text, encoding="utf-8")
    print(text, end="")
    return report


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description=__doc__)
    sub = parser.add_subparsers(dest="command", required=True)

    release = sub.add_parser("validate", help="validate the packaged data and optional predictions")
    release.add_argument("--questions", type=Path, default=DEFAULT_QUESTIONS)
    release.add_argument("--probes", type=Path, default=DEFAULT_PROBES)
    release.add_argument("--skip-videos", action="store_true")
    release.add_argument("--predictions", type=Path)

    inference = sub.add_parser("infer", help="generate captions through a user-supplied Python adapter")
    inference.add_argument("--adapter", type=Path, required=True)
    inference.add_argument("--model-name", required=True)
    inference.add_argument("--model-args", type=parse_object, default={})
    inference.add_argument("--questions", type=Path, default=DEFAULT_QUESTIONS)
    inference.add_argument("--output", type=Path, required=True)
    inference.add_argument("--num-shards", type=int, default=1)
    inference.add_argument("--shard-id", type=int, default=0)
    inference.add_argument("--limit", type=int, default=0)

    judging = sub.add_parser("judge", help="judge caption support for the frozen private probes")
    judging.add_argument("--predictions", type=Path, required=True)
    judging.add_argument("--output", type=Path, required=True)
    judging.add_argument("--questions", type=Path, default=DEFAULT_QUESTIONS)
    judging.add_argument("--probes", type=Path, default=DEFAULT_PROBES)
    judging.add_argument("--base-url", default="http://127.0.0.1:18901/v1")
    judging.add_argument("--api-key", default="EMPTY")
    judging.add_argument("--judge-model", default="qwen-judge")
    judging.add_argument("--workers", type=int, default=32)
    judging.add_argument("--retries", type=int, default=4)
    judging.add_argument("--timeout", type=float, default=90)

    scoring = sub.add_parser("score", help="aggregate complete frozen-probe judgments")
    scoring.add_argument("--judgments", type=Path, required=True)
    scoring.add_argument("--probes", type=Path, default=DEFAULT_PROBES)
    scoring.add_argument("--output", type=Path)
    return parser


def main() -> None:
    parser = build_parser()
    args = parser.parse_args()
    if args.command == "validate":
        report = validate_release(args.questions, args.probes, not args.skip_videos)
        if args.predictions:
            predictions = validate_predictions(args.questions, args.predictions)
            report["predictions"] = len(predictions)
        print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True))
    elif args.command == "infer":
        infer(args)
    elif args.command == "judge":
        judge(args)
    elif args.command == "score":
        score(args)
    else:  # pragma: no cover
        parser.error(f"unknown command: {args.command}")


if __name__ == "__main__":
    main()