File size: 8,043 Bytes
16231ab | 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
"""ETH Zurich binaural sound perception dataset (Vasudevan, Dai, Van Gool, ECCV 2020; data.zip) -> synchronized
10-s image/audio pairs, prepared like 360+x (prepare_360x_outdoor.py).
Layout: <root>/dataset_public/sceneNNNN/ with one 360 video (VIDEO_*_cropped.mp4, 3840x1920 equirectangular, ~5 min)
and LAB-T*.WAV/ holding 8 mono 48 kHz tracks (4 binaural microphone pairs on a Zoom F8). The cropped video is already
time-aligned with the WAV tracks (envelope cross-correlation on 3 scenes: offset 0.00 +- 0.01 s).
Per scene and 10-s segment: the equirectangular frame at the segment midpoint -> 4 perspective views (yaw
0/90/180/270, 90 deg, as every panorama dataset), and the segment of binaural pair 1 (tracks 1 + 2, stereo; tracks
3-4 are broken in scenes 1-27 per the dataset README). One fixed recording site per scene, so split_group = the scene
(no clip of a site is on both sides of a split or fold). License CC BY-NC 4.0 (research use).
"""
from __future__ import annotations
import sys as _sys
from pathlib import Path as _Path
_SCRIPTS = next(_p for _p in _Path(__file__).resolve().parents if _p.name == "scripts")
_sys.path[:0] = [str(_SCRIPTS.parent), str(_SCRIPTS.parent / "models")] + [str(_d) for _d in sorted(_SCRIPTS.rglob("*")) if _d.is_dir() and _d.name != "__pycache__"]
import argparse
import hashlib
import json
import shutil
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import numpy as np
import pandas as pd
import soundfile as sf
from panorama_views import make_views
DATASET = "eth_binaural_zurich"
def grouped_split(groups):
ordered = sorted(set(groups), key=lambda g: hashlib.sha1(g.encode()).hexdigest())
n_train, n_val = round(0.70 * len(ordered)), round(0.15 * len(ordered))
return {g: "train" if i < n_train else "val" if i < n_train + n_val else "test" for i, g in enumerate(ordered)}
def run(cmd):
r = subprocess.run(cmd, capture_output=True, text=True)
if r.returncode:
raise RuntimeError(r.stderr.strip() or f"command failed: {cmd}")
def duration(path: Path) -> float:
r = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],
capture_output=True, text=True)
return float(r.stdout.strip())
def prepare_scene(scene: Path, out: Path, clip_seconds: float, view_size: int, pair: tuple[int, int]):
name = scene.name
video = next(scene.glob("*.mp4"))
wav_dir = next(p for p in scene.iterdir() if p.is_dir() and p.name.upper().endswith(".WAV"))
tracks = [next(wav_dir.glob(f"*_Tr{k}.WAV")) for k in pair]
left, sr = sf.read(tracks[0], dtype="float32")
right, sr2 = sf.read(tracks[1], dtype="float32")
if sr != sr2:
raise RuntimeError(f"sample rates differ in {name}")
n = min(len(left), len(right))
stereo = np.stack([left[:n], right[:n]], 1)
clip_frames = round(clip_seconds * sr)
count = int(min(n / sr, duration(video)) // clip_seconds)
if count < 1:
raise RuntimeError(f"{name} shorter than one clip")
frames_dir, audio_dir, views_dir = out / "panorama_frames" / name, out / "audio", out / "views"
for d in (frames_dir, audio_dir, views_dir):
d.mkdir(parents=True, exist_ok=True)
frames = [frames_dir / f"frame_{i + 1:05d}.jpg" for i in range(count)]
if not all(f.is_file() and f.stat().st_size for f in frames):
for f in frames_dir.glob("frame_*.jpg"):
f.unlink()
run(["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-ss", str(clip_seconds / 2), "-i", str(video),
"-vf", f"fps=1/{clip_seconds}", "-frames:v", str(count), "-q:v", "2", str(frames_dir / "frame_%05d.jpg")])
if not all(f.is_file() and f.stat().st_size for f in frames):
raise RuntimeError(f"midpoint frame extraction incomplete for {name}")
rows = []
for i, frame in enumerate(frames):
stem = f"{name}_{i:04d}"
audio = audio_dir / f"{stem}.wav"
if not audio.exists():
sf.write(audio, stereo[i * clip_frames:(i + 1) * clip_frames], sr, subtype="PCM_24")
views, pano = make_views(frame, views_dir, stem, view_size)
if len(views) != 4 or not pano:
raise RuntimeError(f"expected a four-view panorama for {frame}")
rows.append({"segment_id": stem, "segment_index": i, "segment_start_seconds": i * clip_seconds,
"photo_path": str(views[0].resolve()), "photo_view_paths": "|".join(str(v.resolve()) for v in views),
"audio_path": str(audio.resolve()), "source_video_path": str(video.resolve()),
"audio_tracks": f"Tr{pair[0]}+Tr{pair[1]}"})
return rows
def main():
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--root", type=Path, default=Path("/data/binaural_sound_perception/dataset_public"))
p.add_argument("--output-root", type=Path, default=Path("data/eth_binaural/prepared"))
p.add_argument("--output-manifest", type=Path, default=Path("data/eth_binaural_synchronized_manifest.csv"))
p.add_argument("--clip-seconds", type=float, default=10.0)
p.add_argument("--view-size", type=int, default=512)
p.add_argument("--pair", type=int, nargs=2, default=[1, 2], help="binaural track pair (default tracks 1 + 2)")
p.add_argument("--workers", type=int, default=3)
p.add_argument("--max-scenes", type=int, default=0, help="pilot: first N scenes")
a = p.parse_args()
if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None:
raise SystemExit("ffmpeg/ffprobe are required")
scenes = sorted(d for d in a.root.iterdir() if d.is_dir() and d.name.startswith("scene"))
if a.max_scenes:
scenes = scenes[:a.max_scenes]
split = grouped_split([s.name for s in scenes])
done, failures = {}, []
with ThreadPoolExecutor(max_workers=a.workers) as pool:
futures = {pool.submit(prepare_scene, s, a.output_root, a.clip_seconds, a.view_size, tuple(a.pair)): s for s in scenes}
for k, f in enumerate(as_completed(futures), 1):
s = futures[f]
try:
done[s.name] = f.result()
except Exception as exc:
failures.append({"scene": s.name, "error": str(exc)})
print(f" {k}/{len(scenes)} scenes ({len(failures)} failed)", flush=True)
if failures:
raise SystemExit(f"{len(failures)} scenes failed: {failures[:5]}")
rows = []
for s in scenes:
for item in done[s.name]:
rows.append({"photo_id": f"eth_{item['segment_id']}", "location_id": f"eth_{item['segment_id']}",
"recording_id": f"eth_{s.name}", "parent_location_id": f"eth_site:{s.name}",
"owner_or_session": f"eth_site:{s.name}", "split_group": f"eth_site:{s.name}",
"split": split[s.name], "dataset": DATASET, "source_dataset": DATASET,
"pairing_status": "accepted_synchronized_same_recording", "pairing_strength": "strong",
"use_for_training": True, "city": "zurich", "panorama": True, "license": "CC BY-NC 4.0",
"source_url": "https://github.com/arunbalajeev/binaural-sound-perception", **item})
frame = pd.DataFrame(rows)
if frame.photo_id.duplicated().any() or frame.audio_path.duplicated().any():
raise SystemExit("duplicate segment ids or audio paths")
a.output_manifest.parent.mkdir(parents=True, exist_ok=True)
frame.to_csv(a.output_manifest, index=False)
report = {"scenes": len(scenes), "segments": len(frame), "by_split": frame.split.value_counts().to_dict(),
"segments_per_scene_median": float(frame.groupby("recording_id").size().median())}
a.output_manifest.with_suffix(".summary.json").write_text(json.dumps(report, indent=2))
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
|