Download scripts/data_preparation/targets/extract_audio_targets.py from xiaohaoy/ViewingSoundPAQ: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/data_preparation/targets/extract_audio_targets.py
- Command line
-
hf download hf://xiaohaoy/ViewingSoundPAQ/scripts/data_preparation/targets/extract_audio_targets.py
-
curl -L -o extract_audio_targets.py https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/scripts/data_preparation/targets/extract_audio_targets.py
10.1 kB
| #!/usr/bin/env python3 | |
| 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 | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from tqdm import tqdm | |
| from soundscape_models.audio import ( | |
| analyze_audio, | |
| audio_feature_signature, | |
| fix_duration, | |
| integrated_lufs, | |
| load_mono_audio, | |
| write_float_wav, | |
| ) | |
| from soundscape_models.utils import ( | |
| RunningMoments, | |
| load_config, | |
| resolve_manifest_path, | |
| save_json, | |
| ) | |
| def parse_args() -> argparse.Namespace: | |
| parser = argparse.ArgumentParser(description="Extract mixed-audio ground-truth targets.") | |
| parser.add_argument("--manifest", type=Path, required=True) | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| parser.add_argument("--output-manifest", type=Path, required=True) | |
| parser.add_argument("--config", type=Path, default=Path("configs/baseline.yaml")) | |
| parser.add_argument( | |
| "--crop-mode", | |
| choices=["start", "center", "deterministic-random"], | |
| default="center", | |
| ) | |
| parser.add_argument("--seed", type=int, default=42) | |
| parser.add_argument("--overwrite", action="store_true") | |
| parser.add_argument("--limit", type=int) | |
| return parser.parse_args() | |
| def main() -> None: | |
| args = parse_args() | |
| config = load_config(args.config) | |
| audio_config = config["audio"] | |
| feature_signature = audio_feature_signature(audio_config) | |
| level_target = audio_config.get("level_normalization_lufs") | |
| level_mode = audio_config.get("level_normalization_mode", "clip") | |
| group_column = audio_config.get("level_group_column", "city") | |
| level_tag = "none" if level_target is None else f"{float(level_target):.2f}" | |
| if level_target is not None and level_mode == "group": | |
| level_tag = f"group:{group_column}:{float(level_target):.2f}" | |
| peak_limited_count = 0 | |
| frame = pd.read_csv(args.manifest) | |
| if args.limit is not None: | |
| frame = frame.iloc[: args.limit].copy() | |
| required = {"photo_id", "audio_path", "split"} | |
| missing = required - set(frame.columns) | |
| if missing: | |
| raise SystemExit(f"Manifest is missing columns: {sorted(missing)}") | |
| group_gains: dict[str, float] = {} | |
| group_medians: dict[str, float] = {} | |
| if level_target is not None and level_mode == "group": | |
| if group_column not in frame: | |
| raise SystemExit(f"level_group_column {group_column!r} is not a manifest column") | |
| # Pass 1: source loudness of every clip; each group's gain is set from its TRAIN clips. | |
| sample_rate = int(audio_config["sample_rate"]) | |
| samples = int(round(sample_rate * float(audio_config["duration_seconds"]))) | |
| source = [] | |
| for row in tqdm(frame.itertuples(index=False), total=len(frame), desc="Measuring loudness"): | |
| try: | |
| path = resolve_manifest_path(row.audio_path, asset_root=getattr(row, "asset_root", None), | |
| manifest=args.manifest) | |
| wave, _ = fix_duration(load_mono_audio(path, sample_rate), samples, args.crop_mode, | |
| identifier=str(row.photo_id), seed=args.seed) | |
| source.append(integrated_lufs(np.clip(wave, -1.0, 1.0), sample_rate)) | |
| except Exception: | |
| source.append(float("nan")) | |
| frame["source_lufs"] = source | |
| for group, rows in frame.groupby(group_column): | |
| values = rows.loc[rows.split == "train", "source_lufs"].dropna() | |
| values = values if len(values) else rows.source_lufs.dropna() | |
| group_medians[str(group)] = float(values.median()) | |
| group_gains[str(group)] = float(level_target) - group_medians[str(group)] | |
| print("Per-group gain (dB): " + ", ".join(f"{g} {v:+.1f} (train median {group_medians[g]:.1f} LUFS)" | |
| for g, v in group_gains.items())) | |
| target_dir = args.output_dir / "targets" | |
| waveform_dir = args.output_dir / "waveforms" | |
| target_dir.mkdir(parents=True, exist_ok=True) | |
| waveform_dir.mkdir(parents=True, exist_ok=True) | |
| target_paths: list[str] = [] | |
| waveform_paths: list[str] = [] | |
| status: list[str] = [] | |
| mel_stats = RunningMoments() | |
| envelope_stats = RunningMoments() | |
| lufs_stats = RunningMoments() | |
| for row in tqdm(frame.itertuples(index=False), total=len(frame), desc="Audio targets"): | |
| target_path = (target_dir / f"{row.photo_id}.npz").resolve() | |
| waveform_path = (waveform_dir / f"{row.photo_id}.wav").resolve() | |
| try: | |
| audio_path = resolve_manifest_path( | |
| row.audio_path, | |
| asset_root=getattr(row, "asset_root", None), | |
| manifest=args.manifest, | |
| ) | |
| if args.overwrite or not target_path.exists() or not waveform_path.exists(): | |
| row_config = audio_config | |
| if group_gains: | |
| row_config = {**audio_config, "fixed_gain_db": group_gains[str(getattr(row, group_column))]} | |
| features = analyze_audio( | |
| audio_path, | |
| str(row.photo_id), | |
| row_config, | |
| crop_mode=args.crop_mode, | |
| seed=args.seed, | |
| ) | |
| if not np.isfinite(features["lufs"]): | |
| raise ValueError("integrated LUFS is undefined (silent or too short after decoding)") | |
| np.savez_compressed( | |
| target_path, | |
| mel=features["mel"].astype(np.float32), | |
| loudness_db=features["loudness_db"].astype(np.float32), | |
| lufs=np.float32(features["lufs"]), | |
| sample_rate=np.int32(features["sample_rate"]), | |
| crop_start_sample=np.int64(features["crop_start_sample"]), | |
| original_samples=np.int64(features["original_samples"]), | |
| schema_version=np.array("mixed_audio_targets_v2"), | |
| target_kind=np.array("observed_mixture"), | |
| feature_profile=np.array(audio_config["feature_profile"]), | |
| feature_signature=np.array(feature_signature), | |
| level_normalization=np.array(level_tag), | |
| source_lufs=np.float32(features["source_lufs"]), | |
| level_gain_db=np.float32(features["level_gain_db"]), | |
| peak_limited=np.bool_(features["peak_limited"]), | |
| ) | |
| write_float_wav( | |
| waveform_path, | |
| features["waveform"], | |
| int(features["sample_rate"]), | |
| ) | |
| else: | |
| with np.load(target_path) as existing: | |
| existing_signature = str(existing.get("feature_signature", "")) | |
| existing_level = str(existing.get("level_normalization", "none")) | |
| if existing_level != level_tag: | |
| raise ValueError( | |
| f"existing target has level normalization {existing_level!r}, config wants " | |
| f"{level_tag!r}; use a different --output-dir or --overwrite" | |
| ) | |
| if existing_signature != feature_signature: | |
| raise ValueError( | |
| "existing target uses a different spectrogram profile; rerun with --overwrite" | |
| ) | |
| if str(row.split) == "train": | |
| with np.load(target_path) as data: | |
| mel_stats.update(data["mel"]) | |
| envelope_stats.update(data["loudness_db"]) | |
| lufs_stats.update(float(data["lufs"])) | |
| with np.load(target_path) as data: | |
| peak_limited_count += bool(data.get("peak_limited", False)) | |
| target_paths.append(str(target_path)) | |
| waveform_paths.append(str(waveform_path)) | |
| status.append("ok") | |
| except Exception as exc: | |
| target_paths.append("") | |
| waveform_paths.append("") | |
| status.append(f"error: {exc}") | |
| frame["audio_target_path"] = target_paths | |
| frame["standardized_waveform_path"] = waveform_paths | |
| frame["audio_target_status"] = status | |
| args.output_manifest.parent.mkdir(parents=True, exist_ok=True) | |
| frame.to_csv(args.output_manifest, index=False) | |
| stats = { | |
| "schema_version": "mixed_audio_targets_v2", | |
| "target_kind": "observed_mixture", | |
| "feature_profile": audio_config["feature_profile"], | |
| "feature_signature": feature_signature, | |
| "mel": mel_stats.as_dict(), | |
| "loudness_db": envelope_stats.as_dict(), | |
| "lufs": lufs_stats.as_dict(), | |
| "level_normalization_lufs": level_target, | |
| "level_normalization_mode": level_mode, | |
| "level_group_column": group_column if group_gains else None, | |
| "level_group_gains_db": group_gains or None, | |
| "level_group_train_median_lufs": group_medians or None, | |
| "audio_config": audio_config, | |
| "crop_mode": args.crop_mode, | |
| "seed": args.seed, | |
| } | |
| if level_target is not None and level_mode == "clip": | |
| # LUFS is ~constant after level normalization; floor its std so normalized inputs stay bounded. | |
| stats["lufs"]["std"] = max(float(stats["lufs"]["std"]), 1.0) | |
| save_json(stats, args.output_dir / "normalization_stats.json") | |
| failures = sum(value != "ok" for value in status) | |
| print(f"Wrote {len(frame) - failures:,} target records; failures={failures}") | |
| if level_target is not None: | |
| print(f"Level-normalized to {level_tag} LUFS; peak-limited clips: {peak_limited_count}") | |
| print(f"Manifest: {args.output_manifest}") | |
| print(f"Statistics: {args.output_dir / 'normalization_stats.json'}") | |
| if __name__ == "__main__": | |
| main() | |