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48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
"""
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()