| |
| """ |
| Freeze spatial rendering metadata into test JSON files for deterministic evaluation. |
| |
| This script pre-computes and stores the spatial parameters (SOFA file, mic positions, |
| source positions, HRTF indices) into each test JSON so that every evaluation run |
| produces identical binaural rendering. |
| |
| Usage: |
| conda activate semhear_emma2 |
| python data/freeze_test_spatial_metadata.py --mixtures_dir data/audio_mixtures_old --hrtf_dir data/hrtf |
| """ |
|
|
| import argparse |
| import glob |
| import hashlib |
| import json |
| import os |
| import random |
| import sys |
|
|
| import numpy as np |
|
|
| |
| project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| sys.path.insert(0, project_root) |
|
|
| from data.multi_ch_simulator import Multi_Ch_Simulator |
|
|
|
|
| def freeze_spatial_metadata(mixtures_dir: str, hrtf_dir: str, sr: int = 44100, |
| reverb: bool = True, dry_run: bool = False) -> None: |
| """ |
| For each test JSON in mixtures_dir/test/, compute deterministic spatial |
| rendering params and write them into the JSON file. |
| """ |
| test_dir = os.path.join(mixtures_dir, "test") |
| json_files = sorted(glob.glob(os.path.join(test_dir, "*.json"))) |
|
|
| |
| json_files = [f for f in json_files if not os.path.basename(f).startswith("_")] |
|
|
| if not json_files: |
| print(f"No JSON files found in {test_dir}") |
| return |
|
|
| print(f"Found {len(json_files)} test JSON files in {test_dir}") |
|
|
| |
| simulator_pool = Multi_Ch_Simulator(hrtf_dir, "test", sr, reverb) |
|
|
| updated = 0 |
| skipped = 0 |
|
|
| for json_path in json_files: |
| with open(json_path, "r") as f: |
| metadata = json.load(f) |
|
|
| |
| spatial_labels = ["speech"] |
| for distractor_name in metadata.get("distractors", []): |
| spatial_labels.append(distractor_name) |
| num_sources = len(spatial_labels) |
|
|
| |
| audio_file = json_path.replace(".json", ".wav") |
| seed = int.from_bytes( |
| hashlib.sha256(str(audio_file).encode()).digest()[:4], "little" |
| ) |
|
|
| |
| np.random.seed(seed) |
| random.seed(seed) |
|
|
| |
| sim = simulator_pool.get_random_simulator() |
|
|
| |
| sim.initialize_room_with_random_params( |
| num_sources, 0, spatial_labels, nbackground_sources=0 |
| ) |
|
|
| |
| spatial_meta = sim.get_metadata() |
|
|
| |
| spatial_meta = _make_json_serializable(spatial_meta) |
|
|
| |
| metadata["sofa"] = spatial_meta["sofa"] |
| metadata["mic_positions"] = spatial_meta["mic_positions"] |
| metadata["sources"] = spatial_meta["sources"] |
| metadata["num_background"] = spatial_meta["num_background"] |
| metadata["duration"] = spatial_meta["duration"] |
|
|
| if dry_run: |
| print(f" [dry-run] {os.path.basename(json_path)}: " |
| f"sofa={metadata['sofa']}, " |
| f"sources={len(metadata['sources'])}") |
| skipped += 1 |
| else: |
| with open(json_path, "w") as f: |
| json.dump(metadata, f, indent=2) |
| updated += 1 |
|
|
| if (updated + skipped) % 500 == 0: |
| print(f" Processed {updated + skipped}/{len(json_files)} files...") |
|
|
| print(f"Done: {updated} updated, {skipped} skipped (dry_run={dry_run})") |
|
|
|
|
| def _make_json_serializable(obj): |
| """Recursively convert numpy types to native Python types.""" |
| if isinstance(obj, dict): |
| return {k: _make_json_serializable(v) for k, v in obj.items()} |
| elif isinstance(obj, (list, tuple)): |
| return [_make_json_serializable(item) for item in obj] |
| elif isinstance(obj, np.integer): |
| return int(obj) |
| elif isinstance(obj, np.floating): |
| return float(obj) |
| elif isinstance(obj, np.ndarray): |
| return obj.tolist() |
| return obj |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser( |
| description="Freeze spatial rendering metadata into test JSON files" |
| ) |
| parser.add_argument( |
| "--mixtures_dir", required=True, |
| help="Path to audio_mixtures directory (contains test/ subdir)" |
| ) |
| parser.add_argument( |
| "--hrtf_dir", default="data/hrtf", |
| help="Path to HRTF directory (default: data/hrtf)" |
| ) |
| parser.add_argument( |
| "--sr", type=int, default=44100, |
| help="Sample rate (default: 44100)" |
| ) |
| parser.add_argument( |
| "--no-reverb", action="store_true", |
| help="Disable reverb (use CIPIC only)" |
| ) |
| parser.add_argument( |
| "--dry-run", action="store_true", |
| help="Print what would be written without modifying files" |
| ) |
| args = parser.parse_args() |
|
|
| freeze_spatial_metadata( |
| mixtures_dir=args.mixtures_dir, |
| hrtf_dir=args.hrtf_dir, |
| sr=args.sr, |
| reverb=not args.no_reverb, |
| dry_run=args.dry_run, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|