""" run_param_sweep.py — S-SPADE parameter sweep with residual similarity ranking ================================================================================ PIPELINE -------- 1. Carica test.flac (limitato) e test__3db.flac (versione +3 dB pre-limiter) 2. Normalizza entrambi a -20 LUFS integrato con pyloudnorm 3. Ground-truth residual = somma in fase inversa dei due (= ciò che il limiter ha tolto) 4. Normalizza il residual GT a -3 dBFS 5. Per ogni combinazione di parametri: a. Esegui declip su test.flac b. Normalizza output a -20 LUFS c. Calcola residual = test_lufs + declipped_lufs * (-1) (inv. di fase) d. Normalizza a -3 dBFS e. Confronta GT vs residual_iter con similarità coseno su micro-finestre temporali + frequenziali 6. Stampa ranking finale per similarity media e mediana DIPENDENZE ---------- pip install numpy scipy soundfile pyloudnorm rich (rich è opzionale ma dà una tabella bella) """ import sys import itertools import warnings from dataclasses import dataclass, field, asdict from pathlib import Path from typing import List, Tuple, Dict, Optional import traceback import numpy as np import scipy.signal as sig import soundfile as sf # ── pyloudnorm ─────────────────────────────────────────────────────────────── try: import pyloudnorm as pyln _HAS_PYLN = True except ImportError: _HAS_PYLN = False warnings.warn("pyloudnorm non trovato — installa con: pip install pyloudnorm", stacklevel=1) # ── spade_declip ───────────────────────────────────────────────────────────── try: from spade_declip_v11 import declip, DeclipParams _HAS_SPADE = True except ImportError: _HAS_SPADE = False warnings.warn("spade_declip_v11 non trovato — metti il file nella stessa cartella", stacklevel=1) # ── rich (opzionale) ───────────────────────────────────────────────────────── try: from rich.console import Console from rich.table import Table from rich import print as rprint _console = Console() _HAS_RICH = True except ImportError: _HAS_RICH = False _console = None # ============================================================================= # FILE DI INPUT — modifica qui se i nomi sono diversi # ============================================================================= FILE_LIMITED = "test.flac" # traccia limitata (quella che elaboriamo) FILE_PLUS3DB = "test_3db.flac" # stessa traccia +3 dB (riferimento pre-limiter) LUFS_TARGET = -20.0 # normalizzazione LUFS integrato per entrambe RESIDUAL_DBFS = -3.0 # normalizzazione peak del residual # ============================================================================= # GRIGLIA DEI PARAMETRI DA ESPLORARE # ============================================================================= # Ogni lista può avere uno o più valori. # Il prodotto cartesiano genera tutte le combinazioni da testare. PARAM_GRID = { # ── parametri declipping ───────────────────────────────────────────── "delta_db" : [1.5, 2.0, 2.5, 3.0], "window_length" : [1024, 2048], "hop_length" : [256], # di solito window//4 "eps" : [0.05, 0.1], "max_iter" : [500], # alza a 1000 se hai tempo # ── v11 delimiting ─────────────────────────────────────────────────── "release_ms" : [0.0, 100.0, 250.0], "max_gain_db" : [0.0, 4.0, 6.0], } # Parametri fissi (non cambiano tra le iterazioni) FIXED_PARAMS = dict( algo = "sspade", frame = "rdft", s = 1, r = 1, mode = "soft", multiband = False, macro_expand = False, n_jobs = -1, verbose = False, show_progress= False, ) # Limita il numero massimo di combinazioni da testare (None = tutte) MAX_COMBINATIONS: Optional[int] = None # es. 40 per un test rapido # ============================================================================= # FUNZIONI DI SUPPORTO # ============================================================================= def normalize_lufs(audio: np.ndarray, sr: int, target_lufs: float) -> np.ndarray: """Normalizza audio (N,C) a target_lufs LUFS integrato.""" if not _HAS_PYLN: raise RuntimeError("pyloudnorm richiesto per la normalizzazione LUFS") meter = pyln.Meter(sr) # pyloudnorm vuole (N,) mono o (N,2) stereo loud = meter.integrated_loudness(audio if audio.shape[1] > 1 else audio[:, 0]) if np.isinf(loud): return audio # silenzio — lascia invariato gain_lin = 10 ** ((target_lufs - loud) / 20.0) return audio * gain_lin def normalize_peak_dbfs(audio: np.ndarray, target_dbfs: float) -> np.ndarray: """Normalizza audio al target peak (dBFS).""" peak = np.max(np.abs(audio)) if peak < 1e-12: return audio target_lin = 10 ** (target_dbfs / 20.0) return audio * (target_lin / peak) def compute_residual(a: np.ndarray, b: np.ndarray) -> np.ndarray: """ Residual = a + (-b) (inversione di fase di b). Assicura stessa lunghezza troncando al minimo. """ L = min(a.shape[0], b.shape[0]) return a[:L] - b[:L] # equivalente a a + inv_phase(b) def stft_cosine_similarity( gt: np.ndarray, est: np.ndarray, sr: int, win_samples: int = 2048, hop_samples: int = 512, n_freq_bins: int = 16, # numero di bande di frequenza (mel-like split) ) -> Dict[str, float]: """ Calcola la similarità coseno media tra GT e stima su micro-finestre tempo-frequenziali. Strategia: - STFT di entrambi i residual - Split dell'asse frequenze in `n_freq_bins` bande log-spaced - Per ogni banda e ogni frame: cosine similarity vettoriale - Restituisce mean, median, p10, p90 Input: audio mono 1-D. """ def _stft(x): _, _, Z = sig.stft( x, fs=sr, window="hann", nperseg=win_samples, noverlap=win_samples - hop_samples, boundary=None, padded=False ) return Z # shape: (freqs, time) # Usa solo il canale L se stereo gt_m = gt[:, 0] if gt.ndim == 2 else gt est_m = est[:, 0] if est.ndim == 2 else est L = min(len(gt_m), len(est_m)) Z_gt = _stft(gt_m[:L]) Z_est = _stft(est_m[:L]) n_freqs, n_frames = Z_gt.shape # Suddividi in bande log-spaced edges = np.unique( np.round(np.logspace(0, np.log10(n_freqs), n_freq_bins + 1)).astype(int) ) edges = np.clip(edges, 0, n_freqs) similarities = [] for i in range(len(edges) - 1): f0, f1 = edges[i], edges[i + 1] if f1 <= f0: continue # Per ogni frame temporale: cosine similarity sul vettore di frequenze nella banda g = np.abs(Z_gt[f0:f1, :]) # (band_size, frames) e = np.abs(Z_est[f0:f1, :]) # Cosine similarity per ogni frame dot = np.sum(g * e, axis=0) norm_g = np.sqrt(np.sum(g ** 2, axis=0)) + 1e-12 norm_e = np.sqrt(np.sum(e ** 2, axis=0)) + 1e-12 cos_frame = dot / (norm_g * norm_e) similarities.extend(cos_frame.tolist()) arr = np.array(similarities) return { "mean" : float(np.mean(arr)), "median": float(np.median(arr)), "p10" : float(np.percentile(arr, 10)), "p90" : float(np.percentile(arr, 90)), } # ============================================================================= # PREPARAZIONE GROUND TRUTH # ============================================================================= def prepare_ground_truth(sr_ref: int) -> Tuple[np.ndarray, int]: """ Carica test.flac e test__3db.flac, normalizza a LUFS_TARGET, calcola il residual GT e lo normalizza a RESIDUAL_DBFS. Ritorna (residual_gt, sr). """ print("\n" + "=" * 65) print("CALCOLO GROUND-TRUTH RESIDUAL") print("=" * 65) # Carica limited, sr_l = sf.read(FILE_LIMITED, always_2d=True) plus3db, sr_p = sf.read(FILE_PLUS3DB, always_2d=True) assert sr_l == sr_p, f"Sample rate diversi: {sr_l} vs {sr_p}" sr = sr_l limited = limited.astype(float) plus3db = plus3db.astype(float) print(f" {FILE_LIMITED} : {limited.shape[0]} camp @ {sr} Hz " f"| peak={np.max(np.abs(limited)):.4f}") print(f" {FILE_PLUS3DB}: {plus3db.shape[0]} camp @ {sr} Hz " f"| peak={np.max(np.abs(plus3db)):.4f}") # Normalizza LUFS limited_lufs = normalize_lufs(limited, sr, LUFS_TARGET) plus3db_lufs = normalize_lufs(plus3db, sr, LUFS_TARGET) print(f" Normalizzazione LUFS: target={LUFS_TARGET} dBLUFS") # Residual residual_gt = compute_residual(plus3db_lufs, limited_lufs) residual_gt = normalize_peak_dbfs(residual_gt, RESIDUAL_DBFS) peak_res = np.max(np.abs(residual_gt)) print(f" Residual GT peak normalizzato: {20*np.log10(peak_res+1e-12):.2f} dBFS " f"({residual_gt.shape[0]} camp)") return residual_gt, sr # ============================================================================= # SINGOLA ITERAZIONE DECLIP + RESIDUAL # ============================================================================= def run_iteration( limited_raw: np.ndarray, sr: int, params_dict: dict, residual_gt: np.ndarray, ) -> Optional[Dict]: """ Esegue una singola iterazione di declip con i params forniti, calcola il residual e la similarità con il GT. Ritorna un dizionario con i risultati, o None se fallisce. """ try: # DeclipParams p = DeclipParams( sample_rate = sr, **{k: v for k, v in FIXED_PARAMS.items()}, **params_dict, ) fixed, _ = declip(limited_raw.copy(), p) fixed_2d = fixed[:, None] if fixed.ndim == 1 else fixed # Normalizza output a LUFS_TARGET fixed_lufs = normalize_lufs(fixed_2d, sr, LUFS_TARGET) # Carica anche il limited normalizzato LUFS (ricalcola ogni volta per sicurezza) limited_lufs = normalize_lufs(limited_raw, sr, LUFS_TARGET) # Residual iterazione residual_iter = compute_residual(fixed_lufs, limited_lufs) residual_iter = normalize_peak_dbfs(residual_iter, RESIDUAL_DBFS) # Similarità coseno su micro-finestre TF sim = stft_cosine_similarity(residual_gt, residual_iter, sr) return { "params" : params_dict, "sim_mean" : sim["mean"], "sim_median": sim["median"], "sim_p10" : sim["p10"], "sim_p90" : sim["p90"], } except Exception as exc: print(f" [ERRORE] {exc}") traceback.print_exc() return None # ============================================================================= # STAMPA RISULTATI # ============================================================================= def print_results(results: List[Dict], top_n: int = 20): """Stampa il ranking per sim_mean decrescente.""" results_sorted = sorted(results, key=lambda x: x["sim_mean"], reverse=True) print("\n" + "=" * 65) print(f"RANKING (top {min(top_n, len(results_sorted))} / {len(results_sorted)} iterazioni)") print(f"Metrica principale: similarità coseno media sulle micro-finestre TF") print("=" * 65) if _HAS_RICH: table = Table(show_header=True, header_style="bold cyan") table.add_column("#", style="dim", width=4) table.add_column("mean", justify="right", width=7) table.add_column("median", justify="right", width=7) table.add_column("p10", justify="right", width=7) table.add_column("p90", justify="right", width=7) table.add_column("delta_db", justify="right", width=8) table.add_column("win", justify="right", width=6) table.add_column("hop", justify="right", width=6) table.add_column("eps", justify="right", width=6) table.add_column("max_iter", justify="right", width=8) table.add_column("release_ms", justify="right", width=10) table.add_column("max_gain_db", justify="right", width=11) for rank, r in enumerate(results_sorted[:top_n], 1): p = r["params"] row_style = "green" if rank == 1 else ("yellow" if rank <= 3 else "") table.add_row( str(rank), f"{r['sim_mean']:.4f}", f"{r['sim_median']:.4f}", f"{r['sim_p10']:.4f}", f"{r['sim_p90']:.4f}", str(p.get("delta_db", "—")), str(p.get("window_length", "—")), str(p.get("hop_length", "—")), str(p.get("eps", "—")), str(p.get("max_iter", "—")), str(p.get("release_ms", "—")), str(p.get("max_gain_db", "—")), style=row_style, ) _console.print(table) else: header = ( f"{'#':>3} {'mean':>7} {'med':>7} {'p10':>7} {'p90':>7}" f" {'Δdb':>5} {'win':>5} {'hop':>4} {'eps':>5} " f"{'iter':>5} {'rel_ms':>7} {'gain_db':>8}" ) print(header) print("-" * len(header)) for rank, r in enumerate(results_sorted[:top_n], 1): p = r["params"] print( f"{rank:>3} {r['sim_mean']:>7.4f} {r['sim_median']:>7.4f}" f" {r['sim_p10']:>7.4f} {r['sim_p90']:>7.4f}" f" {p.get('delta_db',0):>5} {p.get('window_length',0):>5}" f" {p.get('hop_length',0):>4} {p.get('eps',0):>5}" f" {p.get('max_iter',0):>5} {p.get('release_ms',0):>7}" f" {p.get('max_gain_db',0):>8}" ) # Parametri migliori best = results_sorted[0] print("\n✓ PARAMETRI MIGLIORI:") for k, v in best["params"].items(): print(f" {k} = {v}") print(f" → sim_mean={best['sim_mean']:.4f} " f"sim_median={best['sim_median']:.4f}") # ============================================================================= # MAIN # ============================================================================= def main(): if not _HAS_PYLN: sys.exit("Installa pyloudnorm prima di eseguire: pip install pyloudnorm") if not _HAS_SPADE: sys.exit("spade_declip_v11.py non trovato nella cartella corrente") # ── Carica il file limitato una sola volta ──────────────────────────── limited_raw, sr = sf.read(FILE_LIMITED, always_2d=True) limited_raw = limited_raw.astype(float) # ── Ground-truth residual ───────────────────────────────────────────── residual_gt, sr = prepare_ground_truth(sr) # ── Genera griglia parametri ────────────────────────────────────────── keys = list(PARAM_GRID.keys()) values = list(PARAM_GRID.values()) combos = list(itertools.product(*values)) if MAX_COMBINATIONS and len(combos) > MAX_COMBINATIONS: # Campionamento stratificato semplice (ogni N) step = len(combos) // MAX_COMBINATIONS combos = combos[::step][:MAX_COMBINATIONS] print(f"\n[INFO] Griglia ridotta a {len(combos)} combinazioni (MAX_COMBINATIONS={MAX_COMBINATIONS})") print(f"\n{'='*65}") print(f"PARAM SWEEP — {len(combos)} combinazioni da testare") print(f"{'='*65}") results = [] for i, combo in enumerate(combos): params_dict = dict(zip(keys, combo)) label = " ".join(f"{k}={v}" for k, v in params_dict.items()) print(f"\n[{i+1:>3}/{len(combos)}] {label}") res = run_iteration(limited_raw, sr, params_dict, residual_gt) if res is not None: print(f" → sim_mean={res['sim_mean']:.4f} " f"sim_median={res['sim_median']:.4f}") results.append(res) else: print(" → SALTATO (errore)") if not results: print("\n[ERRORE] Nessuna iterazione completata.") return print_results(results, top_n=20) # ── Salva CSV con tutti i risultati ─────────────────────────────────── import csv csv_path = "param_sweep_results.csv" fieldnames = ["rank", "sim_mean", "sim_median", "sim_p10", "sim_p90"] + keys results_sorted = sorted(results, key=lambda x: x["sim_mean"], reverse=True) with open(csv_path, "w", newline="") as f: w = csv.DictWriter(f, fieldnames=fieldnames) w.writeheader() for rank, r in enumerate(results_sorted, 1): row = {"rank": rank, "sim_mean": round(r["sim_mean"], 5), "sim_median": round(r["sim_median"], 5), "sim_p10": round(r["sim_p10"], 5), "sim_p90": round(r["sim_p90"], 5)} row.update(r["params"]) w.writerow(row) print(f"\n 📄 Risultati salvati in: {csv_path}") if __name__ == "__main__": main()