Download scripts/fetch_clips.py from facebook/personalized-hearing: direct link, hf CLI and curl.
- Browser
- Download file 6.44 kB
-
https://huggingface.co/datasets/facebook/personalized-hearing/resolve/main/scripts/fetch_clips.py
- Command line
-
hf download hf://datasets/facebook/personalized-hearing/scripts/fetch_clips.py
-
curl -L -o fetch_clips.py https://huggingface.co/datasets/facebook/personalized-hearing/resolve/main/scripts/fetch_clips.py
6.44 kB
| # 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() | |