Download models/soundscape_models/audio.py from xiaohaoy/ViewingSoundPAQ: direct link, hf CLI and curl.
- Browser
- Download file 7.64 kB
-
https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/models/soundscape_models/audio.py
- Command line
-
hf download hf://xiaohaoy/ViewingSoundPAQ/models/soundscape_models/audio.py
-
curl -L -o audio.py https://huggingface.co/xiaohaoy/ViewingSoundPAQ/resolve/main/models/soundscape_models/audio.py
7.64 kB
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import librosa | |
| import numpy as np | |
| import pyloudnorm as pyln | |
| import soundfile as sf | |
| SOUNDAQNET_FEATURE_KEYS = ( | |
| "feature_profile", | |
| "sample_rate", | |
| "n_fft", | |
| "win_length", | |
| "hop_length", | |
| "n_mels", | |
| "f_min", | |
| "f_max", | |
| "window", | |
| "center", | |
| "pad_mode", | |
| "power", | |
| "ref", | |
| "amin", | |
| "top_db", | |
| ) | |
| def audio_feature_signature(config: dict) -> str: | |
| canonical = {key: config.get(key) for key in SOUNDAQNET_FEATURE_KEYS} | |
| payload = json.dumps(canonical, sort_keys=True, separators=(",", ":")) | |
| return hashlib.sha256(payload.encode()).hexdigest()[:16] | |
| def load_mono_audio(path: str | Path, sample_rate: int) -> np.ndarray: | |
| waveform, source_rate = sf.read(path, dtype="float32", always_2d=True) | |
| waveform = waveform.mean(axis=1) | |
| if source_rate != sample_rate: | |
| waveform = librosa.resample( | |
| waveform, orig_sr=source_rate, target_sr=sample_rate, res_type="soxr_hq" | |
| ) | |
| return np.asarray(waveform, dtype=np.float32) | |
| def fix_duration( | |
| waveform: np.ndarray, | |
| target_samples: int, | |
| mode: str, | |
| identifier: str, | |
| seed: int, | |
| ) -> tuple[np.ndarray, int]: | |
| if waveform.size < target_samples: | |
| return np.pad(waveform, (0, target_samples - waveform.size)), 0 | |
| if waveform.size == target_samples: | |
| return waveform, 0 | |
| maximum_start = waveform.size - target_samples | |
| if mode == "start": | |
| start = 0 | |
| elif mode == "center": | |
| start = maximum_start // 2 | |
| elif mode == "deterministic-random": | |
| digest = hashlib.sha256(f"{identifier}:{seed}".encode()).digest() | |
| start = int.from_bytes(digest[:8], "little") % (maximum_start + 1) | |
| else: | |
| raise ValueError(f"Unknown crop mode: {mode}") | |
| return waveform[start : start + target_samples], start | |
| def log_mel_spectrogram( | |
| waveform: np.ndarray, | |
| sample_rate: int, | |
| n_fft: int, | |
| hop_length: int, | |
| win_length: int, | |
| n_mels: int, | |
| f_min: float, | |
| f_max: float, | |
| window: str = "hann", | |
| center: bool = True, | |
| pad_mode: str = "reflect", | |
| power: float = 2.0, | |
| ref: float = 1.0, | |
| amin: float = 1e-10, | |
| top_db: float | None = None, | |
| ) -> np.ndarray: | |
| mel_power = librosa.feature.melspectrogram( | |
| y=waveform, | |
| sr=sample_rate, | |
| n_fft=n_fft, | |
| hop_length=hop_length, | |
| win_length=win_length, | |
| n_mels=n_mels, | |
| fmin=f_min, | |
| fmax=f_max, | |
| window=window, | |
| power=power, | |
| center=center, | |
| pad_mode=pad_mode, | |
| ) | |
| return librosa.power_to_db( | |
| mel_power, | |
| ref=ref, | |
| amin=amin, | |
| top_db=top_db, | |
| ).astype(np.float32) | |
| def frame_loudness_db( | |
| waveform: np.ndarray, n_fft: int, hop_length: int, floor_db: float | |
| ) -> np.ndarray: | |
| rms = librosa.feature.rms( | |
| y=waveform, | |
| frame_length=n_fft, | |
| hop_length=hop_length, | |
| center=True, | |
| pad_mode="reflect", | |
| )[0] | |
| db = 20.0 * np.log10(np.maximum(rms, 10 ** (floor_db / 20.0))) | |
| return np.maximum(db, floor_db).astype(np.float32) | |
| def integrated_lufs(waveform: np.ndarray, sample_rate: int) -> float: | |
| if not np.any(np.abs(waveform) > 1e-8): | |
| return float("nan") | |
| meter = pyln.Meter(sample_rate) | |
| try: | |
| value = float(meter.integrated_loudness(waveform.astype(np.float64))) | |
| except Exception: | |
| return float("nan") | |
| if np.isfinite(value): | |
| return value | |
| # BS.1770 uses an absolute gate, so a valid but unusually low-level recording can | |
| # be reported as -inf. Measure a temporarily boosted copy and subtract the exact | |
| # boost afterward. Targeting a -20 dBFS peak leaves ample headroom and does not | |
| # alter ordinary recordings, which already returned a finite value above. | |
| peak = float(np.max(np.abs(waveform))) | |
| if not np.isfinite(peak) or peak <= 1e-8: | |
| return float("nan") | |
| peak_db = float(20.0 * np.log10(peak)) | |
| boost_db = min(100.0, max(0.0, -20.0 - peak_db)) | |
| if boost_db <= 0.0: | |
| return float("nan") | |
| boosted = waveform.astype(np.float64) * (10.0 ** (boost_db / 20.0)) | |
| try: | |
| boosted_value = float(meter.integrated_loudness(boosted)) | |
| except Exception: | |
| return float("nan") | |
| return boosted_value - boost_db if np.isfinite(boosted_value) else float("nan") | |
| def analyze_audio( | |
| path: str | Path, | |
| identifier: str, | |
| config: dict, | |
| crop_mode: str, | |
| seed: int, | |
| ) -> dict[str, np.ndarray | float | int]: | |
| sample_rate = int(config["sample_rate"]) | |
| target_samples = int(round(sample_rate * float(config["duration_seconds"]))) | |
| waveform = load_mono_audio(path, sample_rate) | |
| original_samples = int(waveform.size) | |
| waveform, crop_start = fix_duration( | |
| waveform, target_samples, crop_mode, identifier=identifier, seed=seed | |
| ) | |
| waveform = np.nan_to_num(waveform, nan=0.0, posinf=1.0, neginf=-1.0) | |
| waveform = np.clip(waveform, -1.0, 1.0).astype(np.float32) | |
| source_lufs = integrated_lufs(waveform, sample_rate) | |
| level_gain_db, peak_limited = 0.0, False | |
| target_lufs = config.get("level_normalization_lufs") | |
| mode = config.get("level_normalization_mode", "clip") | |
| if mode == "group" and config.get("fixed_gain_db") is not None: | |
| # One gain per recording group (e.g. city/recorder): keeps loudness differences between | |
| # places, removes only the group's recorder gain. Set per clip by extract_audio_targets. | |
| level_gain_db = float(config["fixed_gain_db"]) | |
| elif mode == "clip" and target_lufs is not None and np.isfinite(source_lufs): | |
| # Remove uncalibrated recording gain: bring every clip to the same integrated loudness. | |
| level_gain_db = float(target_lufs) - source_lufs | |
| if level_gain_db != 0.0: | |
| waveform = waveform * np.float32(10.0 ** (level_gain_db / 20.0)) | |
| peak = float(np.max(np.abs(waveform))) | |
| if peak > 0.999: | |
| waveform = waveform * np.float32(0.999 / peak) | |
| level_gain_db += float(20.0 * np.log10(0.999 / peak)) | |
| peak_limited = True | |
| waveform = waveform.astype(np.float32) | |
| mel = log_mel_spectrogram( | |
| waveform, | |
| sample_rate, | |
| int(config["n_fft"]), | |
| int(config["hop_length"]), | |
| int(config["win_length"]), | |
| int(config["n_mels"]), | |
| float(config["f_min"]), | |
| float(config["f_max"]), | |
| str(config.get("window", "hann")), | |
| bool(config.get("center", True)), | |
| str(config.get("pad_mode", "reflect")), | |
| float(config.get("power", 2.0)), | |
| float(config.get("ref", 1.0)), | |
| float(config.get("amin", 1e-10)), | |
| config.get("top_db"), | |
| ) | |
| loudness = frame_loudness_db( | |
| waveform, | |
| int(config["n_fft"]), | |
| int(config["hop_length"]), | |
| float(config["loudness_floor_db"]), | |
| ) | |
| frames = min(mel.shape[1], loudness.shape[0]) | |
| mel = mel[:, :frames] | |
| loudness = loudness[:frames] | |
| return { | |
| "waveform": waveform, | |
| "mel": mel, | |
| "loudness_db": loudness, | |
| "lufs": integrated_lufs(waveform, sample_rate), | |
| "source_lufs": source_lufs, | |
| "level_gain_db": level_gain_db, | |
| "peak_limited": peak_limited, | |
| "crop_start_sample": crop_start, | |
| "original_samples": original_samples, | |
| "sample_rate": sample_rate, | |
| } | |
| def write_float_wav(path: str | Path, waveform: np.ndarray, sample_rate: int) -> None: | |
| path = Path(path) | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| sf.write(path, waveform, sample_rate, subtype="FLOAT") | |