File size: 4,426 Bytes
f91d9a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""I/O helpers and standard output layout for LSV benchmarks."""

from __future__ import annotations

import json
import shutil
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable


BENCHMARK_ROOT = Path(__file__).resolve().parents[1]
DATA_DIR = BENCHMARK_ROOT / "data"


@dataclass(frozen=True)
class OutputLayout:
    root: Path

    @property
    def run_config_path(self) -> Path:
        return self.root / "run_config.json"

    def task_dir(self, task_name: str) -> Path:
        return self.root / task_name

    def predictions_path(self, task_name: str) -> Path:
        return self.task_dir(task_name) / "predictions.jsonl"

    def legacy_predictions_path(self, task_name: str) -> Path:
        return self.task_dir(task_name) / "per_video_results.jsonl"

    def shard_path(self, task_name: str, shard_index: int) -> Path:
        return self.task_dir(task_name) / f"predictions_shard_{shard_index:02d}.jsonl"


def read_json(path: Path) -> dict[str, Any]:
    return json.loads(path.read_text(encoding="utf-8"))


def write_json(path: Path, value: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n", encoding="utf-8")


def read_jsonl(path: Path) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    if not path.exists():
        return rows
    with path.open("r", encoding="utf-8") as fh:
        for line in fh:
            line = line.strip()
            if not line:
                continue
            try:
                rows.append(json.loads(line))
            except json.JSONDecodeError:
                continue
    return rows


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


def append_jsonl(path: Path, row: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("a", encoding="utf-8") as fh:
        fh.write(json.dumps(row, ensure_ascii=False) + "\n")


def load_json_manifest(path: Path) -> dict[str, Any]:
    return read_json(path)


def manifest_examples(path: Path) -> list[dict[str, Any]]:
    payload = load_json_manifest(path)
    rows = payload.get("examples")
    if not isinstance(rows, list):
        raise ValueError(f"Manifest has no examples list: {path}")
    return [dict(row) for row in rows if isinstance(row, dict)]


def read_parquet(path: Path) -> list[dict[str, Any]]:
    import pyarrow.parquet as pq

    return pq.read_table(path).to_pylist()


def select_shard(rows: list[dict[str, Any]], num_shards: int, shard_index: int) -> list[dict[str, Any]]:
    if num_shards < 1:
        raise ValueError("num_shards must be >= 1")
    if not (0 <= shard_index < num_shards):
        raise ValueError("shard_index must satisfy 0 <= shard_index < num_shards")
    if num_shards == 1:
        return rows
    return [row for idx, row in enumerate(rows) if idx % num_shards == shard_index]


def candidate_prediction_files(task_dir: Path) -> list[Path]:
    paths = sorted(task_dir.glob("predictions_shard_*.jsonl"))
    if paths:
        return paths
    paths = sorted(task_dir.glob("per_video_results_shard_*.jsonl"))
    if paths:
        return paths
    for name in ("predictions.jsonl", "per_video_results.jsonl"):
        path = task_dir / name
        if path.exists():
            return [path]
    return []


def load_prediction_rows(task_dir: Path, *, sort_key: str = "eval_id") -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    for path in candidate_prediction_files(task_dir):
        rows.extend(read_jsonl(path))
    return sorted(rows, key=lambda row: str(row.get(sort_key) or row.get("video_id") or row.get("eval_id") or ""))


def merge_shards(task_dir: Path, *, sort_key: str = "eval_id") -> list[dict[str, Any]]:
    rows = load_prediction_rows(task_dir, sort_key=sort_key)
    if rows:
        write_jsonl(task_dir / "predictions.jsonl", rows)
    return rows


def copy_legacy_predictions(task_dir: Path) -> None:
    predictions = task_dir / "predictions.jsonl"
    legacy = task_dir / "per_video_results.jsonl"
    if predictions.exists() and not legacy.exists():
        shutil.copyfile(predictions, legacy)