File size: 5,100 Bytes
c585bf5
 
 
 
 
 
 
 
 
 
8694a57
c585bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8694a57
 
c585bf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8694a57
c585bf5
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Verify the released videos and original-resolution frames for inference."""

import argparse
import csv
import json
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from urllib.parse import quote, urlsplit

from extract_frames import relative_file, validate_frame_cache, validate_video


def load_rows(root):
    rows = [json.loads(line) for line in (root / "test.jsonl").read_text(encoding="utf-8").splitlines() if line.strip()]
    if not rows or len({row["id"] for row in rows}) != len(rows):
        raise ValueError("Sample IDs must be unique and the dataset must be nonempty")
    for row in rows:
        if (not isinstance(row["id"], str) or not row["id"].isdigit()
                or str(int(row["id"])) != row["id"]):
            raise ValueError("Sample IDs must be canonical nonnegative integer strings")
        if any(not isinstance(row[key], str) or not row[key].strip() for key in ("question", "answer")):
            raise ValueError("Question and answer must be nonempty strings")
        if row["fps"] != 1 or type(row["n_frames"]) is not int or row["n_frames"] < 1:
            raise ValueError("Expected 1 FPS and a positive integer n_frames")
        relative_file(root, row["video"])
    return rows


def prepare(root, rows, base_url, workers, verify_only=False):
    inventory = {
        row["path"]: row
        for row in map(json.loads, (root / "media.jsonl").read_text(encoding="utf-8").splitlines())
    }
    unique = {}
    for row in rows:
        if row["video"] in unique and unique[row["video"]]["n_frames"] != row["n_frames"]:
            raise ValueError("Conflicting frame counts for the same video")
        unique[row["video"]] = row

    records = [json.loads(line) for line in (root / "frames.jsonl").read_text(encoding="utf-8").splitlines() if line.strip()]
    cached_frames = {record["video"]: record for record in records}
    if len(cached_frames) != len(records) or not set(unique).issubset(cached_frames):
        raise ValueError("Frame manifest must contain unique entries covering all requested videos")

    def process(row):
        source = relative_file(root, row["video"])
        info = inventory[row["video"]]
        if source.stat().st_size != info["bytes"]:
            raise ValueError(f"Video byte size mismatch: {row['video']}")
        if info["n_frames"] != row["n_frames"]:
            raise ValueError("Media inventory and sample frame counts disagree")
        validate_video(source, row["n_frames"])
        validate_frame_cache(root, cached_frames[row["video"]], info)

    with ThreadPoolExecutor(max_workers=workers) as pool:
        list(pool.map(process, unique.values()))
    if verify_only:
        return {"samples": len(rows), "videos": len(unique), "frames": sum(row["n_frames"] for row in unique.values()), "verified": True}

    def url(relative):
        return base_url.rstrip("/") + "/" + quote(relative, safe="/")

    runtime = root / "runtime"
    with (runtime / "video.csv").open("w", newline="", encoding="utf-8") as handle:
        writer = csv.DictWriter(handle, fieldnames=["index", "question", "answer"])
        writer.writeheader()
        writer.writerows({"index": row["id"], "question": row["question"], "answer": row["answer"]} for row in rows)
    with (runtime / "video_manifest.jsonl").open("w", encoding="utf-8") as handle:
        for row in rows:
            n = row["n_frames"]
            record = {
                "case_id": row["id"], "ok": True, "modality": "video",
                "video_url": url(row["video"]), "n_frames": n, "grid_fps": 1.0,
                "duration": float(n), "frame_indices": list(range(n)),
                "frame_urls": [url(f"runtime/frames/{Path(row['video']).stem}/frame_{i:03d}.png") for i in range(n)],
            }
            handle.write(json.dumps(record) + "\n")
    return {"samples": len(rows), "videos": len(unique), "manifest": "runtime/video_manifest.jsonl"}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--data-root", type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument("--media-base-url", help="HTTP(S) base URL serving the entire dataset directory")
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--verify-only", action="store_true", help="Verify media sizes, video layout and original-resolution PNG dimensions and order without preparing inference inputs")
    args = parser.parse_args()
    if args.workers < 1:
        parser.error("--workers must be positive")
    if not args.verify_only:
        parsed = urlsplit(args.media_base_url or "")
        if parsed.scheme not in ("http", "https") or not parsed.netloc or parsed.query or parsed.fragment or parsed.username:
            parser.error("--media-base-url must be an HTTP(S) directory URL without credentials, query or fragment")
    root = args.data_root.resolve()
    print(json.dumps(prepare(root, load_rows(root), args.media_base_url, args.workers, args.verify_only)))


if __name__ == "__main__":
    main()