File size: 6,813 Bytes
4ec41f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Pin the extracted New Generation clips to one reproducible evaluation selection."""
from __future__ import annotations

import argparse
import csv
import hashlib
import json
import sys
from collections import Counter
from pathlib import Path, PurePosixPath

import cv2
import pandas as pd


ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from stateplay.constants import SF3_BUTTON_COLS  # noqa: E402
from stateplay_eval import normalized_label  # noqa: E402


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def dataset_file(root: Path, relative: str) -> Path:
    name = PurePosixPath(relative)
    if name.is_absolute() or ".." in name.parts:
        raise ValueError(f"Unsafe dataset path: {relative}")
    path = (root / name).resolve()
    if not path.is_file() or not path.is_relative_to(root):
        raise FileNotFoundError(f"Missing dataset file: {relative}")
    return path


def verify_packaged_files(root: Path) -> None:
    manifest = root / "qa/file_manifest.sha256"
    lines = manifest.read_text(encoding="utf-8").splitlines()
    if len(lines) < 200:
        raise ValueError(f"Unexpectedly short dataset checksum manifest: {manifest}")
    for line in lines:
        parts = line.split(maxsplit=2)
        if len(parts) == 3:
            expected_hash, expected_size, relative = parts
        elif len(parts) == 2:
            expected_hash, relative = parts
            expected_size = None
        else:
            raise ValueError(f"Malformed dataset checksum entry: {line}")
        path = dataset_file(root, relative)
        if (expected_size is not None and path.stat().st_size != int(expected_size)) or sha256_file(path) != expected_hash:
            raise ValueError(f"Dataset checksum mismatch: {relative}")


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--dataset", type=Path, required=True)
    parser.add_argument("--archive", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()

    dataset = args.dataset.resolve()
    archive = args.archive.resolve()
    if not dataset.is_dir() or not archive.is_file():
        raise FileNotFoundError("Dataset directory and source ZIP must both exist")
    verify_packaged_files(dataset)

    build = json.loads((dataset / "build_info.json").read_text(encoding="utf-8"))
    if (build.get("clip_count"), build.get("game"), build.get("stage")) != (
        100, "sfiii_new_generation", "Ibuki (Round 1)"
    ):
        raise ValueError("This is not the expected 100-clip Ibuki Round 1 release")

    with (dataset / "metadata_state_polish.csv").open(newline="", encoding="utf-8-sig") as handle:
        metadata = list(csv.DictReader(handle))
    with (dataset / "selection_manifest.csv").open(newline="", encoding="utf-8-sig") as handle:
        source_rows = list(csv.DictReader(handle))
    source_by_video = {row["video"]: row for row in source_rows}
    if len(metadata) != 100 or len(source_by_video) != 100:
        raise ValueError("Expected 100 unique metadata and source rows")

    samples = []
    for index, row in enumerate(metadata, start=1):
        source = source_by_video.get(row["video"])
        if source is None or row["action"] != source["action"]:
            raise ValueError(f"Missing matching source identity for {row['video']}")
        label = normalized_label(row["distribution"])
        if label != normalized_label(source["category"]):
            raise ValueError(f"Mechanics label mismatch for {row['video']}")
        video = dataset_file(dataset, row["video"])
        actions = dataset_file(dataset, row["action"])
        frame_actions = pd.read_parquet(actions)
        required = {"timer", "p1_hp", "p2_hp", "p1_meter", "p2_meter", *SF3_BUTTON_COLS}
        if len(frame_actions) != 100 or required - set(frame_actions.columns):
            raise ValueError(f"Invalid action/state table: {actions}")
        cap = cv2.VideoCapture(str(video))
        try:
            frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
            fps = cap.get(cv2.CAP_PROP_FPS)
            valid_first_frame = cap.read()[0]
        finally:
            cap.release()
        if frames != 100 or abs(fps - 20) > 0.1 or not valid_first_frame:
            raise ValueError(f"Invalid reference video: {video} ({frames} frames, {fps} FPS)")
        clip_id = source["clip_id"]
        if video.parent.name != clip_id:
            raise ValueError(f"Clip identity mismatch: {video} versus {clip_id}")
        prompt = row["prompt"].strip()
        if not prompt:
            raise ValueError(f"Empty prompt for {clip_id}")
        samples.append({
            "id": f"ng_{index:03d}",
            "source_kind": "independent_new_generation_selftest",
            "source_id": clip_id,
            "label": label,
            "input_image": None,
            "source_video": str(video),
            "reference_video": str(video),
            "actions": str(actions),
            "prompt": prompt,
            "output_name": f"ng_{index:03d}_{label}_{clip_id}.mp4",
            "identity": {
                "video_sha256": sha256_file(video),
                "actions_file_sha256": sha256_file(actions),
                "source_action_fingerprint": source["action_sha256"],
                "episode_id": source["episode_id"],
            },
        })

    counts = Counter(sample["label"] for sample in samples)
    if set(counts.values()) != {20} or len(counts) != 5:
        raise ValueError(f"Expected 20 clips in each of five classes, got {dict(counts)}")
    result = {
        "benchmark_name": "stateplay_ibuki_round1_new_generation_100_v1",
        "warning": "Independent self-test, not the paper authors' unpublished test set.",
        "source_archive": str(archive),
        "source_archive_sha256": sha256_file(archive),
        "dataset_root": str(dataset),
        "class_counts": dict(sorted(counts.items())),
        "samples": samples,
    }
    output = args.output.resolve()
    output.parent.mkdir(parents=True, exist_ok=True)
    temporary = output.with_suffix(".tmp")
    temporary.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    if output.exists() and output.read_bytes() != temporary.read_bytes():
        temporary.unlink()
        raise ValueError(f"Existing selection differs; refusing to remap prior outputs: {output}")
    temporary.replace(output)
    print(f"Prepared {len(samples)} verified clips in {output}")


if __name__ == "__main__":
    main()