File size: 5,259 Bytes
b1c3148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a1ec2be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31c4aa4
b1c3148
31c4aa4
b1c3148
 
 
 
31c4aa4
 
 
 
 
 
 
 
b1c3148
 
 
a1ec2be
31c4aa4
b1c3148
 
 
 
 
 
 
 
 
 
 
 
a1ec2be
31c4aa4
 
 
 
 
 
 
 
 
b1c3148
 
a1ec2be
 
31c4aa4
a1ec2be
 
31c4aa4
 
 
 
 
 
 
 
 
 
b1c3148
 
 
 
 
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
#!/usr/bin/env python3
"""Reconstruct EgoCoT-Bench processed clips from locally obtained source media.

This script does not download, upload, or redistribute third-party media. Users
must provide source videos obtained from the original dataset providers.
"""

from __future__ import annotations

import argparse
import csv
from pathlib import Path


VIDEO_EXTENSIONS = (".mp4", ".mov", ".mkv", ".avi", ".webm")


def find_source_video(source_root: Path, source_dataset: str, source_video_id: str) -> Path:
    dataset_root = source_root / source_dataset
    candidates = []
    for root in (dataset_root, source_root):
        for ext in VIDEO_EXTENSIONS:
            candidates.append(root / f"{source_video_id}{ext}")
    for candidate in candidates:
        if candidate.exists():
            return candidate
    raise FileNotFoundError(
        f"Could not find source video for {source_dataset}/{source_video_id}. "
        f"Looked under {dataset_root} and {source_root}."
    )


def reconstruct_with_opencv(row: dict[str, str], input_video: Path, output_path: Path) -> None:
    try:
        import cv2
    except ImportError as exc:
        raise RuntimeError(
            "OpenCV is required for reconstruction. Install opencv-python."
        ) from exc

    fps = float(row.get("fps", "4"))
    width = int(row["target_width"])
    height = int(row["target_height"])
    cap = cv2.VideoCapture(str(input_video))
    if not cap.isOpened():
        raise RuntimeError(f"Failed to open source video: {input_video}")

    try:
        raw_fps = cap.get(cv2.CAP_PROP_FPS)
        frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        duration = frame_count / raw_fps if raw_fps > 0 else 0
        target_frame_count = int(duration * fps)
        if target_frame_count <= 0:
            raise RuntimeError(f"Invalid target frame count for {input_video}")

        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        writer = cv2.VideoWriter(str(output_path), fourcc, fps, (width, height))
        if not writer.isOpened():
            raise RuntimeError(f"Failed to open output video writer: {output_path}")
        try:
            for i in range(target_frame_count):
                target_time = i / fps
                raw_frame_idx = int(round(target_time * raw_fps))
                if raw_frame_idx >= frame_count:
                    raw_frame_idx = frame_count - 1
                cap.set(cv2.CAP_PROP_POS_FRAMES, raw_frame_idx)
                success, frame = cap.read()
                if not success:
                    continue
                if frame.shape[1] != width or frame.shape[0] != height:
                    frame = cv2.resize(frame, (width, height))
                writer.write(frame)
        finally:
            writer.release()
    finally:
        cap.release()


def reconstruct_row(
    row: dict[str, str],
    source_root: Path,
    output_root: Path,
    dry_run: bool,
) -> tuple[str, str | None]:
    if row.get("source_dataset") == "Self-recorded":
        return "self_recorded", None
    rel_output = Path(row["expected_local_output_path"])
    if rel_output.is_absolute():
        raise ValueError(f"expected_local_output_path must be relative: {rel_output}")
    output_path = output_root / rel_output
    if output_path.exists():
        return "existing", None

    try:
        input_video = find_source_video(source_root, row["source_dataset"], row["source_video_id"])
    except FileNotFoundError:
        return "missing_source", f"{row.get('source_dataset')}/{row.get('source_video_id')}"

    output_path.parent.mkdir(parents=True, exist_ok=True)

    if not dry_run:
        reconstruct_with_opencv(row, input_video, output_path)
    return ("dry_run" if dry_run else "reconstructed"), None


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--manifest", default="manifests/media_reconstruction.csv")
    parser.add_argument("--source-root", required=True)
    parser.add_argument("--output-root", default="media_reconstructed")
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    source_root = Path(args.source_root)
    output_root = Path(args.output_root)
    seen_outputs: set[str] = set()
    missing_sources: set[str] = set()
    counts = {
        "reconstructed": 0,
        "dry_run": 0,
        "existing": 0,
        "missing_source": 0,
        "self_recorded": 0,
        "duplicate": 0,
    }
    with Path(args.manifest).open(newline="", encoding="utf-8") as handle:
        for row in csv.DictReader(handle):
            output_key = row.get("expected_local_output_path", "")
            if output_key in seen_outputs:
                counts["duplicate"] += 1
                continue
            seen_outputs.add(output_key)
            status, missing_source = reconstruct_row(row, source_root, output_root, args.dry_run)
            counts[status] += 1
            if missing_source:
                missing_sources.add(missing_source)
    if missing_sources:
        print("Missing source videos:")
        for source in sorted(missing_sources):
            print(source)
    else:
        print("No missing source videos.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())