File size: 10,397 Bytes
cb8518a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3


from __future__ import annotations

import argparse
import json
import os
import re
from collections import OrderedDict
from pathlib import Path
from typing import Any

import numpy as np


PROJECT_ROOT = Path(__file__).resolve().parents[1]
FRAME_SUFFIX_RE = re.compile(r"^(?P<case>.+)_f(?P<frame>\d+)$")


def _display_path(path: Path) -> str:
    try:
        return os.path.relpath(path.resolve(), PROJECT_ROOT)
    except Exception:
        return str(path)


def _load_records(path: Path) -> list[dict[str, Any]]:
    if not path.exists():
        raise FileNotFoundError(f"Missing input manifest: {path}")

    if path.suffix.lower() == ".jsonl":
        records: list[dict[str, Any]] = []
        for line_no, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
            raw = line.strip()
            if not raw:
                continue
            obj = json.loads(raw)
            if not isinstance(obj, dict):
                raise ValueError(f"Expected JSON object at {path}:{line_no}")
            records.append(obj)
        return records

    payload = json.loads(path.read_text(encoding="utf-8"))
    if isinstance(payload, list):
        if not all(isinstance(item, dict) for item in payload):
            raise ValueError(f"Expected a list of JSON objects in {path}")
        return list(payload)
    if isinstance(payload, dict):
        samples = payload.get("samples")
        if isinstance(samples, list) and all(isinstance(item, dict) for item in samples):
            return list(samples)
        return [payload]
    raise ValueError(f"Unsupported JSON payload in {path}")


def _sample_id(row: dict[str, Any]) -> str:
    sample_id = row.get("sample_id") or row.get("id")
    if not sample_id:
        raise ValueError("Missing sample_id/id")
    return str(sample_id)


def _case_and_frame(row: dict[str, Any]) -> tuple[str, int | None]:
    if row.get("case_id"):
        case_id = str(row["case_id"])
    else:
        sample_id = _sample_id(row)
        match = FRAME_SUFFIX_RE.match(sample_id)
        case_id = match.group("case") if match else sample_id

    frame_value = row.get("frame")
    if isinstance(frame_value, (int, np.integer)):
        return case_id, int(frame_value)
    if isinstance(frame_value, str) and frame_value.strip().isdigit():
        return case_id, int(frame_value.strip())

    sample_id = _sample_id(row)
    match = FRAME_SUFFIX_RE.match(sample_id)
    if match:
        return case_id, int(match.group("frame"))
    return case_id, None


def _sort_key(row: dict[str, Any]) -> tuple[int, int, str]:
    _, frame = _case_and_frame(row)
    sample_id = _sample_id(row)
    if frame is None:
        return (1, 10**9, sample_id)
    return (0, frame, sample_id)


def _even_indices(total: int, count: int) -> list[int]:
    if total <= 0 or count <= 0:
        return []
    if count >= total:
        return list(range(total))
    return np.linspace(0, total - 1, num=count, dtype=int).tolist()


def _augment_row(
    row: dict[str, Any],
    *,
    benchmark_track: str,
    case_id: str,
    selected_frames: list[int],
    selected_sample_ids: list[str],
    source_sample_ids: list[str],
    source_frames: list[int | None],
    track_rank: int,
    source_manifest: str,
) -> dict[str, Any]:
    out = dict(row)
    out["case_id"] = case_id
    out["benchmark_track"] = benchmark_track
    out["track_rank"] = track_rank
    out["selected_frames"] = selected_frames
    out["selected_sample_ids"] = selected_sample_ids
    out["source_sample_ids"] = source_sample_ids
    out["source_frames"] = source_frames
    out["source_sample_count"] = len(source_sample_ids)
    out["source_manifest"] = source_manifest
    if "frame" not in out or out["frame"] is None:
        _, frame = _case_and_frame(row)
        if frame is not None:
            out["frame"] = frame
    return out


def build_track_manifests(
    input_paths: list[Path],
    out_dir: Path,
    *,
    dynamic_frame_count: int = 7,
    include_single_frame_dynamic: bool = True,
) -> dict[str, Any]:
    if dynamic_frame_count <= 0:
        raise ValueError("dynamic_frame_count must be > 0")

    out_dir.mkdir(parents=True, exist_ok=True)

    rows_by_case: "OrderedDict[str, list[tuple[dict[str, Any], Path]]]" = OrderedDict()
    seen_sample_ids: set[str] = set()
    source_files: list[str] = []

    for path in input_paths:
        source_files.append(_display_path(path))
        for row in _load_records(path):
            sample_id = _sample_id(row)
            if sample_id in seen_sample_ids:
                continue
            seen_sample_ids.add(sample_id)
            case_id, _ = _case_and_frame(row)
            rows_by_case.setdefault(case_id, []).append((row, path))

    static_rows: list[dict[str, Any]] = []
    dynamic_rows: list[dict[str, Any]] = []
    case_index: list[dict[str, Any]] = []

    for case_id, rows_and_sources in rows_by_case.items():
        rows_sorted = sorted(rows_and_sources, key=lambda item: _sort_key(item[0]))
        rows = [row for row, _ in rows_sorted]
        source_manifest = _display_path(rows_sorted[0][1]) if rows_sorted else ""
        source_sample_ids = [_sample_id(row) for row in rows]
        source_frames = [_case_and_frame(row)[1] for row in rows]

        static_source = next((row for row in rows if _case_and_frame(row)[1] == 1), None)
        if static_source is None:
            static_source = rows[0]
        static_frames = [_case_and_frame(static_source)[1]]
        if static_frames[0] is None:
            static_frames = []
        static_row = _augment_row(
            static_source,
            benchmark_track="static",
            case_id=case_id,
            selected_frames=static_frames,
            selected_sample_ids=[_sample_id(static_source)],
            source_sample_ids=source_sample_ids,
            source_frames=source_frames,
            track_rank=0,
            source_manifest=source_manifest,
        )
        static_rows.append(static_row)

        dynamic_selected_rows: list[tuple[dict[str, Any], int]] = []
        if len(rows) == 1 and not include_single_frame_dynamic:
            dynamic_selected_rows = []
        else:
            selected_indices = _even_indices(len(rows), dynamic_frame_count)
            dynamic_selected_rows = [(rows[idx], rank) for rank, idx in enumerate(selected_indices)]

        dynamic_selected_frames = []
        dynamic_selected_ids = []
        for row, _ in dynamic_selected_rows:
            _, frame = _case_and_frame(row)
            if frame is not None:
                dynamic_selected_frames.append(frame)
            dynamic_selected_ids.append(_sample_id(row))

        for row, rank in dynamic_selected_rows:
            dynamic_rows.append(
                _augment_row(
                    row,
                    benchmark_track="dynamic",
                    case_id=case_id,
                    selected_frames=dynamic_selected_frames,
                    selected_sample_ids=dynamic_selected_ids,
                    source_sample_ids=source_sample_ids,
                    source_frames=source_frames,
                    track_rank=rank,
                    source_manifest=source_manifest,
                )
            )

        case_index.append(
            {
                "case_id": case_id,
                "source_sample_ids": source_sample_ids,
                "source_frames": source_frames,
                "source_sample_count": len(source_sample_ids),
                "static_sample_id": _sample_id(static_source),
                "static_frame": static_frames[0] if static_frames else None,
                "dynamic_sample_ids": dynamic_selected_ids,
                "dynamic_frames": dynamic_selected_frames,
                "dynamic_sample_count": len(dynamic_selected_ids),
            }
        )

    static_path = out_dir / "static.jsonl"
    dynamic_path = out_dir / "dynamic.jsonl"
    case_index_path = out_dir / "case_index.json"
    summary_path = out_dir / "track_summary.json"

    with static_path.open("w", encoding="utf-8") as f:
        for row in static_rows:
            f.write(json.dumps(row, ensure_ascii=False) + "\n")

    with dynamic_path.open("w", encoding="utf-8") as f:
        for row in dynamic_rows:
            f.write(json.dumps(row, ensure_ascii=False) + "\n")

    case_index_path.write_text(json.dumps(case_index, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")

    summary = {
        "source_files": source_files,
        "case_count": len(rows_by_case),
        "static_row_count": len(static_rows),
        "dynamic_row_count": len(dynamic_rows),
        "dynamic_frame_count": dynamic_frame_count,
        "include_single_frame_dynamic": include_single_frame_dynamic,
        "static_manifest": _display_path(static_path),
        "dynamic_manifest": _display_path(dynamic_path),
        "case_index": _display_path(case_index_path),
    }
    summary_path.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    return {
        "summary": summary,
        "case_index": case_index,
        "static_rows": static_rows,
        "dynamic_rows": dynamic_rows,
    }


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(description="Split manifests into static and dynamic tracks")
    parser.add_argument(
        "--inputs",
        nargs="+",
        required=True,
        help="Input JSON or JSONL manifests",
    )
    parser.add_argument("--out_dir", required=True, help="Output directory for track manifests")
    parser.add_argument("--dynamic_frame_count", type=int, default=7, help="Frames to keep per dynamic case")
    parser.add_argument(
        "--include_single_frame_dynamic",
        action=argparse.BooleanOptionalAction,
        default=True,
        help="Keep singleton cases in the dynamic track",
    )
    return parser


def main() -> None:
    args = build_parser().parse_args()
    input_paths = [Path(p) for p in args.inputs]
    out_dir = Path(args.out_dir)
    result = build_track_manifests(
        input_paths,
        out_dir,
        dynamic_frame_count=args.dynamic_frame_count,
        include_single_frame_dynamic=args.include_single_frame_dynamic,
    )
    print(json.dumps(result["summary"], indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()