File size: 4,414 Bytes
6461f0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Point-wise benchmark JSON loader.

The expected schema is a flat JSON list of records of the form::

    {
      "video_name": "000434_c.mp4",
      "video_path": "videos/000434_c.mp4",   # relative to the JSON file
      "prompt": "...",
      "source": "vs2",
      "metadata": {
        "visual_score": 4,
        "t2v_score": 4,
        "phy_score": 4
      }
    }

``video_path`` is interpreted relative to the directory that contains the
JSON file (and may also be absolute).
"""
from __future__ import annotations

import json
import os
from typing import Any, Tuple


def _json_records(payload: Any, data_path: str) -> list[dict[str, Any]]:
    if not isinstance(payload, list):
        raise ValueError(
            f"JSON data must be a list of records: {data_path} "
            f"(got {type(payload).__name__})"
        )
    if not all(isinstance(item, dict) for item in payload):
        raise ValueError(f"JSON data must contain objects only: {data_path}")
    return payload


def _resolve_video_path(base_dir: str, video_path: str) -> str:
    """Resolve a record's ``video_path`` against the JSON file's directory."""
    if not isinstance(video_path, str) or not video_path:
        return ""
    if os.path.isabs(video_path):
        return video_path
    return os.path.normpath(os.path.join(base_dir, video_path))


def load_pointwise_data(
    data_path: str,
    num_samples: str = "all",
) -> Tuple[list[dict[str, Any]], list[dict[str, Any]]]:
    """Load a point-wise benchmark JSON.

    Parameters
    ----------
    data_path : str
        Path to the benchmark JSON file.
    num_samples : str
        Either ``"all"`` or a positive integer (as a string) capping the
        number of records.

    Returns
    -------
    (raw_prompts, expanded)
        raw_prompts : list of de-duplicated prompts with their source row
                      indices (handy for any prompt-level step).
        expanded    : list of per-video records ready for scoring.
    """
    data_path = os.path.abspath(data_path)
    base_dir = os.path.dirname(data_path)

    with open(data_path, "r", encoding="utf-8") as f:
        records = _json_records(json.load(f), data_path)
    print(f"[data] Loaded {len(records)} videos from {data_path}")

    if num_samples != "all":
        records = records[: int(num_samples)]
        print(f"[data] Truncated to {len(records)} videos")

    prompt_to_index: dict[str, int] = {}
    raw_prompts: list[dict[str, Any]] = []
    expanded: list[dict[str, Any]] = []

    for row_idx, item in enumerate(records):
        video_name = str(item["video_name"])
        prompt_text = str(item["prompt"])
        source_index = prompt_to_index.get(prompt_text)
        if source_index is None:
            source_index = len(raw_prompts)
            prompt_to_index[prompt_text] = source_index
            raw_prompts.append(
                {"prompt": prompt_text, "prompt_id": source_index, "source_rows": []}
            )
        raw_prompts[source_index]["source_rows"].append(row_idx)

        rel_video_path = item.get("video_path", "")
        local_path = _resolve_video_path(base_dir, rel_video_path)
        source = str(item.get("source", "")).strip()
        metadata = item.get("metadata", {}) or {}
        if not isinstance(metadata, dict):
            metadata = {}

        expanded.append(
            {
                "video_id": f"{row_idx}_{os.path.splitext(video_name)[0]}",
                "video_name": video_name,
                "caption": prompt_text,
                "video_path": rel_video_path,
                "video_local_path": local_path,
                "source": source,
                "source_index": source_index,
                "source_row_index": row_idx,
                "metadata": metadata,
            }
        )

    print(
        f"[data] Unique prompts: {len(raw_prompts)}; videos to score: {len(expanded)}"
    )
    return raw_prompts, expanded


def ensure_video_local(item: dict[str, Any]) -> str:
    """Validate that the local video file exists; return its absolute path."""
    local_path = item.get("video_local_path")
    if (
        isinstance(local_path, str)
        and local_path
        and os.path.exists(local_path)
        and os.path.getsize(local_path) > 0
    ):
        return local_path
    raise FileNotFoundError(
        f"Video not found: {local_path or item.get('video_name')}"
    )