File size: 6,439 Bytes
adb8450
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

"""Rebuild the audio-visual clips that the benchmark sessions refer to.

The dataset stores AudioSet clip IDs ("Y" + YouTube ID), not media. This script
looks up each clip's start time in the AudioSet segment CSVs, downloads the
ten-second segment from YouTube, and writes

    <out-dir>/<asset_id>/frames/frame_00.jpg ... frame_09.jpg
    <out-dir>/<asset_id>/audio.wav

Frames are spread evenly from the first to the last frame of the clip. Clips are
shared between users, so each clip is stored once. Clips that can no longer be
downloaded are listed in <out-dir>/missing.txt.

Requires yt-dlp and ffmpeg/ffprobe on PATH.

Usage:
    python scripts/fetch_clips.py --data-dir data --out-dir media \\
        --segments eval_segments.csv balanced_train_segments.csv unbalanced_train_segments.csv
"""

from __future__ import annotations

import argparse
import csv
import json
import subprocess
import sys
import tempfile
from pathlib import Path

FRAME_COUNT = 10


def load_segments(paths: list[Path]) -> dict[str, tuple[float, float]]:
    """YouTube ID -> (start, end) in seconds, from the AudioSet segment CSVs."""
    segments: dict[str, tuple[float, float]] = {}
    for path in paths:
        with path.open(newline="") as handle:
            for row in csv.reader(handle, skipinitialspace=True):
                if not row or row[0].startswith("#"):
                    continue
                segments[row[0]] = (float(row[1]), float(row[2]))
    return segments


def session_assets(data_dir: Path, users: set[str] | None) -> set[str]:
    """Every clip ID used by a session of the selected users."""
    assets: set[str] = set()
    for path in sorted(data_dir.glob("*/7.1_dialogue_enhanced.json")):
        user_id = path.parent.name
        if users and user_id not in users:
            continue
        record = json.loads(path.read_text())
        record = record[0] if isinstance(record, list) else record
        assets.update(session["selected_asset_id"] for session in record["sessions"])
    return assets


def youtube_id(asset_id: str) -> str:
    return asset_id[1:] if len(asset_id) == 12 and asset_id.startswith("Y") else asset_id


def download_segment(video_id: str, start: float, end: float, target: Path) -> None:
    subprocess.run(
        [
            "yt-dlp",
            "--quiet",
            "--no-warnings",
            "--download-sections",
            f"*{start}-{end}",
            "--force-keyframes-at-cuts",
            "-f",
            "bv*+ba/b",
            "--merge-output-format",
            "mp4",
            "-o",
            str(target),
            f"https://www.youtube.com/watch?v={video_id}",
        ],
        check=True,
    )


def duration(video: Path) -> float:
    result = subprocess.run(
        [
            "ffprobe",
            "-v",
            "error",
            "-show_entries",
            "format=duration",
            "-of",
            "default=noprint_wrappers=1:nokey=1",
            str(video),
        ],
        check=True,
        capture_output=True,
        text=True,
    )
    return float(result.stdout.strip())


def write_media(video: Path, clip_dir: Path) -> None:
    frames_dir = clip_dir / "frames"
    frames_dir.mkdir(parents=True, exist_ok=True)
    # Stop a little short of the end so the last seek still lands on a frame.
    last = max(duration(video) - 0.05, 0.0)
    for index in range(FRAME_COUNT):
        moment = index * last / (FRAME_COUNT - 1)
        subprocess.run(
            [
                "ffmpeg",
                "-y",
                "-loglevel",
                "error",
                "-ss",
                f"{moment:.3f}",
                "-i",
                str(video),
                "-frames:v",
                "1",
                "-q:v",
                "2",
                str(frames_dir / f"frame_{index:02d}.jpg"),
            ],
            check=True,
        )
    subprocess.run(
        [
            "ffmpeg",
            "-y",
            "-loglevel",
            "error",
            "-i",
            str(video),
            "-vn",
            "-acodec",
            "pcm_s16le",
            str(clip_dir / "audio.wav"),
        ],
        check=True,
    )


def is_complete(clip_dir: Path) -> bool:
    return (clip_dir / "audio.wav").exists() and len(
        list((clip_dir / "frames").glob("*.jpg"))
    ) == FRAME_COUNT


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("--data-dir", type=Path, default=Path("data"))
    parser.add_argument("--out-dir", type=Path, default=Path("media"))
    parser.add_argument("--segments", type=Path, nargs="+", required=True, help="AudioSet segment CSVs")
    parser.add_argument("--users", default="", help="Comma-separated user IDs (default: all)")
    args = parser.parse_args()

    users = {u.strip() for u in args.users.split(",") if u.strip()} or None
    segments = load_segments(args.segments)
    assets = sorted(session_assets(args.data_dir, users))
    args.out_dir.mkdir(parents=True, exist_ok=True)
    print(f"{len(assets)} clips to fetch", file=sys.stderr)

    missing: list[str] = []
    for number, asset_id in enumerate(assets, start=1):
        clip_dir = args.out_dir / asset_id
        if is_complete(clip_dir):
            continue
        video_id = youtube_id(asset_id)
        if video_id not in segments:
            missing.append(f"{asset_id}\tnot in the segment CSVs")
            continue
        start, end = segments[video_id]
        try:
            with tempfile.TemporaryDirectory() as tmp:
                video = Path(tmp) / "clip.mp4"
                download_segment(video_id, start, end, video)
                write_media(video, clip_dir)
        except subprocess.CalledProcessError as error:
            missing.append(f"{asset_id}\t{error.cmd[0]} failed")
            continue
        print(f"[{number}/{len(assets)}] {asset_id}", file=sys.stderr)

    (args.out_dir / "missing.txt").write_text("".join(f"{line}\n" for line in missing))
    print(f"done; {len(missing)} clips unavailable (see {args.out_dir / 'missing.txt'})", file=sys.stderr)


if __name__ == "__main__":
    main()