File size: 5,887 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
#!/usr/bin/env python3
"""Validate one versioned StatePlay archive and pin its 100 evaluation cases."""
from __future__ import annotations

import argparse
import csv
import json
from collections import Counter
from pathlib import Path

import cv2
import pandas as pd

from prepare_new_generation_benchmark import dataset_file, sha256_file, verify_packaged_files
from stateplay.constants import SF3_BUTTON_COLS
from stateplay_eval import normalized_label


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("--archive-version", choices=("test_03", "test_04"), required=True)
    parser.add_argument("--expected-release", choices=("test_02", "test_03"), 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("Extracted dataset and source ZIP must both exist")
    verify_packaged_files(dataset)
    build = json.loads((dataset / "build_info.json").read_text(encoding="utf-8"))
    expected = (100, "sfiii_new_generation", "Ibuki (Round 1)", args.expected_release)
    observed = (build.get("clip_count"), build.get("game"), build.get("stage"), build.get("release_name"))
    if observed != expected or build.get("fps") != 20 or build.get("frames_per_clip") != 100:
        raise ValueError(f"Unexpected archive release metadata: {observed}")

    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_rows) != 100 or len(source_by_video) != 100:
        raise ValueError("Expected 100 unique metadata and source rows")

    prefix = args.archive_version.replace("test_", "t")
    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: {row['video']}")
        label = normalized_label(row["distribution"])
        if label != normalized_label(source["category"]):
            raise ValueError(f"Mechanics category mismatch: {row['video']}")
        video = dataset_file(dataset, row["video"])
        actions = dataset_file(dataset, row["action"])
        if video.parent.name != source["clip_id"]:
            raise ValueError(f"Clip identity mismatch: {video}")
        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)
            first_frame_ok = cap.read()[0]
        finally:
            cap.release()
        if frames != 100 or abs(fps - 20) > 0.1 or not first_frame_ok:
            raise ValueError(f"Invalid reference video: {video} ({frames=} {fps=})")
        prompt = row["prompt"].strip()
        if not prompt:
            raise ValueError(f"Empty prompt for {video}")
        sample_id = f"{prefix}_{index:03d}"
        samples.append({
            "id": sample_id,
            "source_kind": "independent_versioned_selftest",
            "source_id": source["clip_id"],
            "label": label,
            "input_image": None,
            "source_video": str(video),
            "reference_video": str(video),
            "actions": str(actions),
            "prompt": prompt,
            "output_name": f"{sample_id}_{label}_{source['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(item["label"] for item in samples)
    if len(counts) != 5 or dict(counts) != {
        normalized_label(label): int(count) for label, count in build["class_counts"].items()
    }:
        raise ValueError(f"Class counts differ from build_info: {dict(counts)}")
    result = {
        "benchmark_name": f"stateplay_{args.archive_version}_archive_100_v1",
        "warning": "Independent self-test, not the paper authors' unpublished test set.",
        "archive_version": args.archive_version,
        "internal_release_name": args.expected_release,
        "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 outputs: {output}")
    temporary.replace(output)
    print(f"Prepared {len(samples)} verified {args.archive_version} clips from internal {args.expected_release}: {output}")


if __name__ == "__main__":
    main()