#!/usr/bin/env python3 """Build leakage-aware manifests for synchronized external audio-visual datasets.""" 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 csv import hashlib import json import math import os import shutil import subprocess from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path ROOT = _SCRIPTS.parent def read_table(path: Path, delimiter: str = ",") -> list[dict[str, str]]: with path.open("r", encoding="utf-8-sig", newline="") as handle: return list(csv.DictReader(handle, delimiter=delimiter)) def grouped_split(groups: list[str], train: float = 0.70, val: float = 0.15) -> dict[str, str]: unique = sorted(set(groups), key=lambda value: hashlib.sha1(value.encode()).hexdigest()) if len(unique) < 3: return {group: "test" for group in unique} n_train = max(1, round(len(unique) * train)) n_val = max(1, round(len(unique) * val)) if n_train + n_val >= len(unique): n_train = max(1, len(unique) - 2) n_val = 1 return { group: "train" if i < n_train else "val" if i < n_train + n_val else "test" for i, group in enumerate(unique) } def spatial_block(lat: float, lon: float, metres: float = 2000.0) -> str: x = lon * 111_320.0 * math.cos(math.radians(lat)) y = lat * 110_540.0 return f"{math.floor(x / metres)}_{math.floor(y / metres)}" def extract_frame(video: Path, frame: Path, seconds: float) -> tuple[Path, str | None]: if frame.exists() and frame.stat().st_size > 0: return frame, None frame.parent.mkdir(parents=True, exist_ok=True) temporary = frame.with_name(frame.name + ".part.jpg") command = [ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-ss", str(seconds), "-i", str(video), "-frames:v", "1", "-q:v", "2", str(temporary), ] result = subprocess.run(command, capture_output=True, text=True) if result.returncode != 0 or not temporary.exists() or temporary.stat().st_size == 0: temporary.unlink(missing_ok=True) return frame, (result.stderr.strip() or f"ffmpeg exit {result.returncode}") os.replace(temporary, frame) return frame, None def extract_frames(tasks: list[tuple[Path, Path, float]], workers: int) -> list[dict[str, str]]: if not tasks: return [] if shutil.which("ffmpeg") is None: raise RuntimeError("ffmpeg is required to extract synchronized still frames") failures: list[dict[str, str]] = [] with ThreadPoolExecutor(max_workers=workers) as pool: futures = {pool.submit(extract_frame, *task): task for task in tasks} for future in as_completed(futures): frame, error = future.result() if error: failures.append({"frame": str(frame), "error": error}) return failures def base_row(dataset: str, sample_id: str, photo: Path, audio: Path, split: str, group: str) -> dict[str, object]: return { "photo_id": sample_id, "photo_path": str(photo.resolve()), "audio_path": str(audio.resolve()), "owner_or_session": group, "split_group": group, "split": split, "dataset": dataset, "pairing_status": "accepted_synchronized_same_recording", "pairing_strength": "strong", "use_for_training": True, } def prepare_urban() -> tuple[list[dict[str, object]], dict[str, object]]: root = ROOT / "data" / "urban_soundscapes_world" media = root / "extracted" metadata = read_table(root / "USotW_metadata.csv") splits = grouped_split([row["City"] for row in metadata]) rows: list[dict[str, object]] = [] missing: list[str] = [] for source in metadata: recording = source["Recording"] photo = media / "panoramic" / source["Image filename"] audio = media / "binaural" / source["Binaural filename"] ambisonic = media / "ambisonics" / source["Ambisonic filename"] if not photo.is_file() or not audio.is_file(): missing.append(recording) continue row = base_row("urban_soundscapes_world", f"usotw_{recording}", photo, audio, splits[source["City"]], f"usotw_city:{source['City']}") row.update({ "recording_id": recording, "city": source["City"], "location": source["Location"], "latitude": source["Latitude"], "longitude": source["Longitude"], "recording_date": source["Recording date"], "measured_laeq": source["LAeq,1min"], "ambisonic_path": str(ambisonic.resolve()) if ambisonic.is_file() else "", "video_path": "", }) rows.append(row) return rows, {"metadata_rows": len(metadata), "accepted": len(rows), "missing_recordings": missing} def prepare_lion(extract: bool, workers: int) -> tuple[list[dict[str, object]], dict[str, object]]: root = ROOT / "data" / "lion_city_soundscapes" metadata = {row["lcs_id"]: row for row in read_table(root / "metadata.tsv", "\t")} candidates: list[tuple[str, Path, Path, Path]] = [] for site, source in sorted(metadata.items()): folder = root / "one_minute" / site video = folder / f"{site}_1min_Insta360.mp4" audio = folder / f"{site}_1min_SQobold_bin.wav" frame = root / "frames" / f"{site}_midpoint.jpg" if video.exists() and audio.exists(): candidates.append((site, video, audio, frame)) failures = extract_frames([(video, frame, 30.0) for _, video, _, frame in candidates], workers) if extract else [] failed_frames = {item["frame"] for item in failures} blocks = [] for site, _, _, _ in candidates: source = metadata[site] blocks.append(spatial_block(float(source["lcs_latitude"]), float(source["lcs_longitude"]))) splits = grouped_split(blocks) rows: list[dict[str, object]] = [] for site, video, audio, frame in candidates: source = metadata[site] block = spatial_block(float(source["lcs_latitude"]), float(source["lcs_longitude"])) if str(frame) in failed_frames or not frame.exists(): continue row = base_row("lion_city_soundscapes", f"lion_{site}", frame, audio, splits[block], f"lion_block_2km:{block}") row.update({ "recording_id": site, "city": "Singapore", "location": source["lcs_description"], "latitude": source["lcs_latitude"], "longitude": source["lcs_longitude"], "recording_date": source["lcs_date"], "measured_laeq": source["insitu_spl_1min_LR_eavg"], "ambisonic_path": str((root / "one_minute" / site / f"{site}_1min_Zylia_19ch.wav").resolve()), "video_path": str(video.resolve()), }) rows.append(row) return rows, {"metadata_rows": len(metadata), "media_pairs": len(candidates), "accepted": len(rows), "frame_failures": failures} def prepare_tau(extract: bool, workers: int) -> tuple[list[dict[str, object]], dict[str, object]]: root = ROOT / "data" / "tau_urban_audio_visual_2021" media = root / "extracted" meta_root = media if (media / "meta.csv").exists() else root / "metadata_preview" metadata = read_table(meta_root / "meta.csv", "\t") official_test = { row["filename_audio"].replace("\\", "/").lower() for row in read_table(meta_root / "evaluation_setup" / "fold1_test.csv", "\t") } train_groups = [row["identifier"] for row in metadata if row["filename_audio"].replace("\\", "/").lower() not in official_test] provisional = grouped_split(train_groups, train=0.90, val=0.05) train_val = {group: "train" if split == "train" else "val" for group, split in provisional.items()} tasks: list[tuple[Path, Path, float]] = [] candidates: list[tuple[dict[str, str], Path, Path, Path, str]] = [] for source in metadata: audio = media / source["filename_audio"] video = media / source["filename_video"] stem = Path(source["filename_video"]).stem frame = root / "frames" / f"{stem}_midpoint.jpg" if not audio.exists() or not video.exists(): continue split = "test" if source["filename_audio"].replace("\\", "/").lower() in official_test else train_val[source["identifier"]] candidates.append((source, audio, video, frame, split)) tasks.append((video, frame, 5.0)) failures = extract_frames(tasks, workers) if extract else [] failed_frames = {item["frame"] for item in failures} rows: list[dict[str, object]] = [] for source, audio, video, frame, split in candidates: if str(frame) in failed_frames or not frame.exists(): continue identifier = source["identifier"] city = identifier.rsplit("-", 1)[0] sample_id = f"tau_{Path(source['filename_audio']).stem}" row = base_row("tau_urban_audio_visual_2021", sample_id, frame, audio, split, f"tau_location:{identifier}") row.update({ "recording_id": Path(source["filename_audio"]).stem, "city": city, "location": identifier, "latitude": "", "longitude": "", "recording_date": "", "measured_laeq": "", "ambisonic_path": "", "video_path": str(video.resolve()), "scene_label": source["scene_label"], }) rows.append(row) return rows, {"metadata_rows": len(metadata), "media_pairs": len(candidates), "accepted": len(rows), "frame_failures": failures} def prepare_urbansas(extract: bool, workers: int) -> tuple[list[dict[str, object]], dict[str, object]]: """Prepare only the Montevideo/MAVD portion of Urbansas. The labeled Urbansas release republishes 540 TAU street-traffic clips alongside 540 MAVD clips from five Montevideo locations. TAU is already present as its own corpus, so those 540 European clips must never enter this manifest. """ root = ROOT / "data" / "urbansas" media = root / "extracted" annotation_root = media / "annotations" video_annotations = read_table(annotation_root / "video_annotations.csv") audio_annotations = read_table(annotation_root / "audio_annotations.csv") tau_cities = { row["city"].strip().lower() for row in video_annotations if row.get("subset", "").strip().lower() == "tau" } if not tau_cities: raise RuntimeError("Urbansas annotations did not identify any TAU cities") audio_by_stem: dict[str, Path] = {} video_by_stem: dict[str, Path] = {} for path in media.rglob("*.wav"): if "__MACOSX" in path.parts or path.name.startswith("._"): continue if path.stem in audio_by_stem: raise RuntimeError(f"Duplicate Urbansas audio stem: {path.stem}") audio_by_stem[path.stem] = path for path in media.rglob("*.mp4"): if "__MACOSX" in path.parts or path.name.startswith("._"): continue if path.stem in video_by_stem: raise RuntimeError(f"Duplicate Urbansas video stem: {path.stem}") video_by_stem[path.stem] = path common = sorted(set(audio_by_stem) & set(video_by_stem)) tau_stems = { stem for stem in common if any(stem.lower().startswith(city) for city in tau_cities) } retained = [stem for stem in common if stem not in tau_stems] if len(common) != 1080 or len(retained) != 540 or len(tau_stems) != 540: raise RuntimeError( "Unexpected Urbansas media inventory: " f"paired={len(common)}, Montevideo={len(retained)}, TAU={len(tau_stems)}; " "expected 1080/540/540 for Zenodo record 6658386 (labeled set)" ) # Defense in depth: no retained file stem may match the already prepared TAU corpus. tau_manifest = ROOT / "data" / "tau_urban_audio_visual_2021_synchronized_manifest.csv" existing_tau_stems: set[str] = set() if tau_manifest.exists(): for row in read_table(tau_manifest): for field in ("recording_id", "audio_path", "video_path"): value = row.get(field, "") if value: existing_tau_stems.add(Path(value).stem.lower()) overlap = sorted(stem for stem in retained if stem.lower() in existing_tau_stems) if overlap: raise RuntimeError(f"Urbansas Montevideo selection overlaps TAU: {overlap[:10]}") locations = {stem: stem.split("_", 1)[0] for stem in retained} # The five physical MAVD locations are kept intact, producing a 3/1/1 split. splits = grouped_split(list(locations.values()), train=0.60, val=0.20) labeled_video = {row["filename"] for row in video_annotations} labeled_audio = {row["filename"] for row in audio_annotations} labels_by_stem: dict[str, set[str]] = {} for source in (*video_annotations, *audio_annotations): label = source.get("label", "").strip() if label and label != "-1": labels_by_stem.setdefault(source["filename"], set()).add(label) candidates: list[tuple[str, str, Path, Path, Path]] = [] tasks: list[tuple[Path, Path, float]] = [] for stem in retained: location = locations[stem] audio = audio_by_stem[stem] video = video_by_stem[stem] frame = root / "frames" / f"{stem}_midpoint.jpg" candidates.append((stem, location, audio, video, frame)) tasks.append((video, frame, 5.0)) failures = extract_frames(tasks, workers) if extract else [] failed_frames = {item["frame"] for item in failures} rows: list[dict[str, object]] = [] for stem, location, audio, video, frame in candidates: if str(frame) in failed_frames or not frame.exists(): continue row = base_row( "urbansas_montevideo", f"urbansas_{stem}", frame, audio, splits[location], f"urbansas_location:{location}", ) row.update({ "recording_id": stem, "location_id": location, "city": "Montevideo", "location": location, "latitude": "", "longitude": "", "recording_date": "", "measured_laeq": "", "ambisonic_path": "", "video_path": str(video.resolve()), "is_audio_annotated": stem in labeled_audio, "is_video_annotated": stem in labeled_video, "urbansas_event_labels": ";".join(sorted(labels_by_stem.get(stem, set()))), "license": "CC BY 4.0", "source_url": "https://doi.org/10.5281/zenodo.6658386", }) rows.append(row) split_locations = { split: sorted(location for location, assigned in splits.items() if assigned == split) for split in ("train", "val", "test") } return rows, { "media_audio": len(audio_by_stem), "media_video": len(video_by_stem), "media_pairs": len(common), "excluded_tau_pairs": len(tau_stems), "retained_montevideo_pairs": len(retained), "existing_tau_overlap": len(overlap), "physical_locations": len(set(locations.values())), "split_locations": split_locations, "annotated_retained_clips": len((labeled_audio | labeled_video) & set(retained)), "accepted": len(rows), "frame_failures": failures, } def write_manifest(name: str, rows: list[dict[str, object]], report: dict[str, object]) -> None: output = ROOT / "data" / f"{name}_synchronized_manifest.csv" report_path = output.with_suffix(".quality.json") output.parent.mkdir(parents=True, exist_ok=True) fields: list[str] = [] for row in rows: for key in row: if key not in fields: fields.append(key) with output.open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=fields) writer.writeheader() writer.writerows(rows) report.update({ "manifest": str(output.resolve()), "rows": len(rows), "split_counts": {split: sum(row["split"] == split for row in rows) for split in ("train", "val", "test")}, "pairing_rule": "Only synchronized media from the same released recording are accepted.", }) report_path.write_text(json.dumps(report, indent=2), encoding="utf-8") print(json.dumps(report, indent=2)) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--dataset", choices=("urban", "lion", "tau", "urbansas", "all"), default="all") parser.add_argument("--extract-frames", action="store_true") parser.add_argument("--workers", type=int, default=4) args = parser.parse_args() selected = ("urban", "lion", "tau", "urbansas") if args.dataset == "all" else (args.dataset,) for name in selected: if name == "urban": rows, report = prepare_urban() write_manifest("urban_soundscapes_world", rows, report) elif name == "lion": rows, report = prepare_lion(args.extract_frames, args.workers) write_manifest("lion_city_soundscapes", rows, report) elif name == "tau": rows, report = prepare_tau(args.extract_frames, args.workers) write_manifest("tau_urban_audio_visual_2021", rows, report) else: rows, report = prepare_urbansas(args.extract_frames, args.workers) write_manifest("urbansas_montevideo", rows, report) if __name__ == "__main__": main()