File size: 4,053 Bytes
d37698e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Score localization-given-labels predictions against a materialized parquet split."""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

# Allow `python scripts/score_predictions.py` from the dataset root.
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from localization.schema import (  # noqa: E402
    GoldSegment,
    LabelSpec,
    PredictionResult,
)
from localization.score import score_episode, summarize_event_rows  # noqa: E402


def _read_jsonl(path: Path) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    with path.open() as handle:
        for line in handle:
            if line.strip():
                rows.append(json.loads(line))
    return rows


def _load_parquet_rows(path: Path) -> list[dict[str, Any]]:
    try:
        import pyarrow.parquet as pq
    except ImportError as exc:  # pragma: no cover
        raise SystemExit(
            "pyarrow is required to read dataset parquet files"
        ) from exc
    return pq.read_table(path).to_pylist()


def _prediction_from_row(row: dict[str, Any]) -> PredictionResult:
    if "labels" in row:
        return PredictionResult.model_validate({"labels": row["labels"]})
    if "prediction" in row:
        return PredictionResult.model_validate(row["prediction"])
    raise ValueError(
        f"prediction row for {row.get('id') or row.get('episode_id')!r} "
        "must contain 'labels' or 'prediction'"
    )


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(
        description="Score localization-given-labels predictions.jsonl"
    )
    parser.add_argument(
        "--data",
        type=Path,
        required=True,
        help="Path to train.parquet or test.parquet",
    )
    parser.add_argument(
        "--preds",
        type=Path,
        required=True,
        help="JSONL with one object per episode: {id|episode_id, labels: [...]}",
    )
    parser.add_argument(
        "--out",
        type=Path,
        default=None,
        help="Optional path for per-event IoU JSONL",
    )
    parser.add_argument(
        "--summary",
        type=Path,
        default=None,
        help="Optional path for summary JSON (default: stdout)",
    )
    args = parser.parse_args(argv)

    episodes = {str(row["id"]): row for row in _load_parquet_rows(args.data)}
    pred_rows = _read_jsonl(args.preds)

    all_event_rows: list[dict[str, Any]] = []
    missing: list[str] = []
    for pred_row in pred_rows:
        episode_id = str(pred_row.get("id") or pred_row.get("episode_id") or "")
        if not episode_id or episode_id not in episodes:
            missing.append(episode_id or "<missing-id>")
            continue
        episode = episodes[episode_id]
        gold = [GoldSegment.from_dict(seg) for seg in episode["gold_segments"]]
        specs = [LabelSpec.from_dict(spec) for spec in episode["label_specs"]]
        prediction = _prediction_from_row(pred_row)
        event_rows, _diagnostics = score_episode(
            episode_id=episode_id,
            family=str(episode["family"]),
            gold_segments=gold,
            specs=specs,
            prediction=prediction,
        )
        all_event_rows.extend(event_rows)

    summary = summarize_event_rows(all_event_rows)
    summary["episodes_scored"] = len({row["episode_id"] for row in all_event_rows})
    summary["episodes_missing_from_data"] = missing

    if args.out is not None:
        args.out.parent.mkdir(parents=True, exist_ok=True)
        with args.out.open("w") as handle:
            for row in all_event_rows:
                handle.write(json.dumps(row) + "\n")

    text = json.dumps(summary, indent=2) + "\n"
    if args.summary is not None:
        args.summary.parent.mkdir(parents=True, exist_ok=True)
        args.summary.write_text(text)
    else:
        sys.stdout.write(text)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())