Download scripts/data_preparation/datasets/prepare_singapore_dataset.py from xiaohaoy/ViewingSoundPAQ: direct link, hf CLI and curl.
- Browser
- Download file 9.89 kB
-
https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/data_preparation/datasets/prepare_singapore_dataset.py
- Command line
-
hf download hf://xiaohaoy/ViewingSoundPAQ/scripts/data_preparation/datasets/prepare_singapore_dataset.py
-
curl -L -o prepare_singapore_dataset.py https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/data_preparation/datasets/prepare_singapore_dataset.py
9.89 kB
| #!/usr/bin/env python3 | |
| """Prepare geocoded Singapore panorama/video locations as an external evaluation manifest.""" | |
| 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 json | |
| import math | |
| import re | |
| import shutil | |
| import subprocess | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| import soundfile as sf | |
| from panorama_views import make_views | |
| LOCATION = re.compile(r"^L_([+-]?\d+(?:\.\d+)?)_\s*([+-]?\d+(?:\.\d+)?)$") | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--source-root", type=Path, default=Path("dataset/Singapore")) | |
| parser.add_argument("--output-root", type=Path, default=Path("dataset/Singapore_prepared")) | |
| parser.add_argument("--manifest", type=Path, default=Path("data/singapore_manifest.csv")) | |
| parser.add_argument("--report", type=Path, default=Path("data/singapore_manifest.quality.json")) | |
| parser.add_argument("--ffmpeg", type=Path) | |
| parser.add_argument("--clip-seconds", type=float, default=10.0) | |
| parser.add_argument("--min-clip-seconds", type=float, default=9.5) | |
| parser.add_argument("--sample-rate", type=int, default=16_000) | |
| parser.add_argument("--view-size", type=int, default=512) | |
| parser.add_argument("--block-m", type=float, default=500.0) | |
| parser.add_argument("--overwrite-audio", action="store_true") | |
| return parser.parse_args() | |
| def find_ffmpeg(explicit: Path | None) -> Path: | |
| candidates = [explicit, Path(shutil.which("ffmpeg")) if shutil.which("ffmpeg") else None] | |
| if sys.platform == "win32": | |
| candidates.append(Path(sys.executable).parent / "Library/bin/ffmpeg.exe") | |
| for candidate in candidates: | |
| if candidate and candidate.exists(): | |
| return candidate.resolve() | |
| raise SystemExit("ffmpeg not found; pass --ffmpeg or install it in the conda environment") | |
| def parse_dba(path: Path) -> dict: | |
| frame = pd.read_csv(path) | |
| values = pd.to_numeric(frame["Values"].astype(str).str.extract(r"([+-]?\d+(?:\.\d+)?)")[0]) | |
| timestamps = pd.to_datetime(frame["Time"].astype(str), format="%Y%m%d%H%M%S", errors="coerce") | |
| return { | |
| "dba_samples": int(values.notna().sum()), | |
| "dba_mean": float(values.mean()), | |
| "dba_median": float(values.median()), | |
| "dba_std": float(values.std()), | |
| "dba_min": float(values.min()), | |
| "dba_max": float(values.max()), | |
| "dba_start": timestamps.min().isoformat() if timestamps.notna().any() else "", | |
| "dba_end": timestamps.max().isoformat() if timestamps.notna().any() else "", | |
| } | |
| def extract_audio(ffmpeg: Path, video: Path, target: Path, sample_rate: int, overwrite: bool) -> None: | |
| if target.exists() and not overwrite: | |
| return | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| partial = target.with_suffix(".partial.wav") | |
| command = [ | |
| str(ffmpeg), "-hide_banner", "-loglevel", "error", "-y", "-i", str(video), | |
| "-vn", "-ac", "1", "-ar", str(sample_rate), "-c:a", "pcm_s16le", str(partial), | |
| ] | |
| subprocess.run(command, check=True) | |
| partial.replace(target) | |
| def block_id(lon: float, lat: float, lon0: float, lat0: float, block_m: float) -> str: | |
| x = (lon - lon0) * math.cos(math.radians(lat0)) * 111_320.0 | |
| y = (lat - lat0) * 110_540.0 | |
| return f"singapore:{math.floor(x / block_m)}_{math.floor(y / block_m)}" | |
| def main() -> None: | |
| args = parse_args() | |
| source, output = args.source_root.resolve(), args.output_root.resolve() | |
| ffmpeg = find_ffmpeg(args.ffmpeg) | |
| locations = [] | |
| for folder in sorted(path for path in source.iterdir() if path.is_dir()): | |
| match = LOCATION.match(folder.name) | |
| if not match: | |
| raise ValueError(f"cannot parse coordinates from {folder.name!r}") | |
| lat, lon = map(float, match.groups()) | |
| required = [folder / "Panoramic.jpg", folder / "video.mp4", folder / "Intensity.csv"] | |
| missing = [str(path) for path in required if not path.exists()] | |
| if missing: | |
| raise FileNotFoundError(f"{folder.name}: missing {missing}") | |
| locations.append({ | |
| "folder": folder, "lat": lat, "lon": lon, | |
| "directional_source_views": len(list(folder.glob("M_*.jpg"))), | |
| **parse_dba(folder / "Intensity.csv"), | |
| }) | |
| lat0 = float(np.mean([row["lat"] for row in locations])) | |
| lon0 = float(np.mean([row["lon"] for row in locations])) | |
| rows, dropped_tails = [], [] | |
| for index, location in enumerate(locations): | |
| location_id = f"sg_{index:03d}" | |
| views, panorama = make_views( | |
| location["folder"] / "Panoramic.jpg", output / "views", location_id, | |
| args.view_size, min_aspect=1.8, | |
| ) | |
| full_audio = output / "full_audio" / f"{location_id}.wav" | |
| extract_audio( | |
| ffmpeg, location["folder"] / "video.mp4", full_audio, | |
| args.sample_rate, args.overwrite_audio, | |
| ) | |
| info = sf.info(full_audio) | |
| samples_per_clip = round(args.clip_seconds * info.samplerate) | |
| with sf.SoundFile(full_audio) as handle: | |
| clip_index = 0 | |
| while True: | |
| waveform = handle.read(samples_per_clip, dtype="float32", always_2d=False) | |
| if not len(waveform): | |
| break | |
| duration = len(waveform) / info.samplerate | |
| if duration < args.min_clip_seconds: | |
| dropped_tails.append({"location_id": location_id, "seconds": duration}) | |
| break | |
| clip = output / "clips" / location_id / f"clip_{clip_index:03d}.wav" | |
| clip.parent.mkdir(parents=True, exist_ok=True) | |
| if not clip.exists() or args.overwrite_audio: | |
| sf.write(clip, waveform, info.samplerate, subtype="PCM_16") | |
| relative_views = [path.relative_to(output).as_posix() for path in views] | |
| rows.append({ | |
| "photo_id": f"{location_id}_c{clip_index:03d}", | |
| "location_id": location_id, | |
| "city": "singapore", | |
| "clip_index": clip_index, | |
| "lon": location["lon"], "lat": location["lat"], | |
| "split": "external_test", | |
| "split_group": block_id(location["lon"], location["lat"], lon0, lat0, args.block_m), | |
| "photo_path": relative_views[0], | |
| "photo_view_paths": "|".join(relative_views), | |
| "source_image_path": str((location["folder"] / "Panoramic.jpg").resolve()), | |
| "panorama": panorama, | |
| "audio_path": clip.relative_to(output).as_posix(), | |
| "asset_root": str(output), | |
| "image_source": "NUS Visual-soundscapes field panorama", | |
| "source_dataset": "Sensing urban soundscapes from street view imagery", | |
| "source_url": "https://github.com/ualsg/Visual-soundscapes", | |
| "source_doi": "10.1016/j.compenvurbsys.2022.101915", | |
| "license": "CC BY-NC-SA 4.0", | |
| "pairing_status": "verified_same_location_field_collection", | |
| "use_for_training": False, | |
| "source_video_path": str((location["folder"] / "video.mp4").resolve()), | |
| "source_audio_start_seconds": clip_index * args.clip_seconds, | |
| "source_audio_duration_seconds": duration, | |
| "source_directional_view_count": location["directional_source_views"], | |
| **{key: value for key, value in location.items() if key.startswith("dba_")}, | |
| }) | |
| clip_index += 1 | |
| manifest = pd.DataFrame(rows) | |
| args.manifest.parent.mkdir(parents=True, exist_ok=True) | |
| manifest.to_csv(args.manifest, index=False) | |
| report = { | |
| "source_root": str(source), "output_root": str(output), | |
| "source_dataset": "Sensing urban soundscapes from street view imagery", | |
| "source_url": "https://github.com/ualsg/Visual-soundscapes", | |
| "source_doi": "10.1016/j.compenvurbsys.2022.101915", | |
| "license": "CC BY-NC-SA 4.0", | |
| "paper_reported_singapore_locations": 43, | |
| "pairing_status": "verified_same_location_field_collection", | |
| "eligible_for_training": False, | |
| "reservation_reason": "held out for geographic generalization evaluation before any training use", | |
| "ffmpeg": str(ffmpeg), "locations": len(locations), "clips": len(manifest), | |
| "total_audio_hours": float(manifest.source_audio_duration_seconds.sum() / 3600), | |
| "panoramas": len(locations), "generated_views_per_location": 4, | |
| "source_directional_view_counts": pd.Series( | |
| [row["directional_source_views"] for row in locations] | |
| ).value_counts().sort_index().to_dict(), | |
| "dropped_short_tails": dropped_tails, | |
| "split": "external_test", | |
| "notes": [ | |
| "All four model views are generated from the complete 8000x2000 panorama.", | |
| "Supplied M_*.jpg counts vary from 5 to 9 and are retained only as source metadata.", | |
| "dBA series is summarized per location; absolute video-to-meter time alignment is unavailable.", | |
| "The paper reports 43 Singapore investigation points; this supplied folder contains 41.", | |
| ], | |
| } | |
| args.report.parent.mkdir(parents=True, exist_ok=True) | |
| args.report.write_text(json.dumps(report, indent=2), encoding="utf-8") | |
| print(json.dumps(report, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |