File size: 25,102 Bytes
4656421
1bfa935
 
 
 
 
 
 
 
66a8297
3a50c1c
1bfa935
 
 
 
 
 
 
 
 
40355de
3e3a76e
1bfa935
66a8297
 
 
 
 
 
 
 
 
 
 
 
 
 
3a50c1c
 
 
53e45f1
3a50c1c
53e45f1
3a50c1c
66a8297
1bfa935
53e45f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bfa935
 
569f62f
 
 
1bfa935
569f62f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1bfa935
 
 
 
 
bbb9d09
1bfa935
 
 
 
 
 
 
5915ef8
1bfa935
 
 
 
 
 
48e1ce4
1bfa935
 
 
 
 
 
 
 
 
 
 
 
9b25b66
 
 
1bfa935
 
 
 
 
 
 
 
 
 
 
 
90573cb
1bfa935
 
 
90573cb
 
 
 
 
 
 
48e1ce4
90573cb
1bfa935
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40355de
 
 
 
1bfa935
32e9732
1bfa935
 
 
40355de
3e3a76e
40355de
 
bbb9d09
40355de
 
bbb9d09
40355de
 
bbb9d09
40355de
 
 
 
 
 
48e1ce4
 
 
 
 
 
 
 
 
 
 
 
 
 
3e3a76e
48e1ce4
 
 
 
 
 
 
 
 
 
 
40355de
 
 
 
 
 
 
 
 
 
e304cef
9b25b66
40355de
 
9b25b66
 
 
40355de
9b25b66
 
 
 
0c4dc06
9b25b66
32e9732
 
 
3e3a76e
6bd65db
bbb9d09
6bd65db
40355de
6bd65db
 
bbb9d09
1bfa935
48e1ce4
 
d78ba89
 
48e1ce4
6bd65db
1bfa935
 
bbb9d09
40355de
1bfa935
 
 
bbb9d09
9b25b66
 
6bd65db
 
 
 
 
9b25b66
6bd65db
 
48e1ce4
 
 
 
 
 
 
40355de
6bd65db
 
 
 
 
 
89f014b
 
 
 
6bd65db
 
 
 
 
 
0c4dc06
40355de
6bd65db
9b25b66
40355de
9b25b66
6bd65db
 
 
dfd1025
6bd65db
3e3a76e
6bd65db
 
 
bbb9d09
e298d4c
 
 
9b25b66
bbb9d09
9b25b66
bbb9d09
9b25b66
 
 
 
 
 
6bd65db
90573cb
 
1bfa935
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32e9732
1bfa935
 
 
 
6bd65db
9b25b66
1bfa935
 
 
 
 
 
 
 
 
 
 
 
 
3816c03
1bfa935
 
 
 
 
 
 
 
9b25b66
 
 
 
85830b2
 
 
 
 
 
 
 
 
 
1bfa935
 
 
 
 
 
 
 
 
 
 
 
 
9b25b66
40355de
569f62f
a089213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
569f62f
 
 
 
 
 
 
 
 
 
 
 
1bfa935
569f62f
 
a089213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b25b66
32e9732
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f4d4abb
d78ba89
5d17045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b25b66
 
6bd65db
9b25b66
6bd65db
9b25b66
 
 
40355de
9b25b66
 
 
 
 
 
 
 
 
6bd65db
32e9732
 
 
 
 
 
9b25b66
 
 
f4d4abb
211cca8
 
 
 
f4d4abb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48e1ce4
 
 
 
 
 
 
 
 
 
 
 
 
 
1bfa935
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
import spaces
import gradio as gr
import numpy as np
from scipy.io.wavfile import read
import matplotlib.pyplot as plt
import torch
from torch import Tensor
import math
import yaml
import os
from huggingface_hub import hf_hub_download, snapshot_download
import json
import pyloudnorm as pyln
from hydra.utils import instantiate
from soxr import resample
from functools import partial, reduce
from itertools import accumulate
from torchcomp import coef2ms, ms2coef
from copy import deepcopy
from pathlib import Path
from typing import Tuple, List, Optional, Union, Callable
from os import environ

# Download AFx-Rep model and config files
os.makedirs("tmp", exist_ok=True)
ckpt_path = hf_hub_download(
    repo_id="csteinmetz1/afx-rep",
    filename="afx-rep.ckpt",
    local_dir="tmp",
    local_files_only=False,
)
config_path = hf_hub_download(
    repo_id="csteinmetz1/afx-rep",
    filename="config.yaml",
    local_dir="tmp",
    local_files_only=False,
)
preset_path = snapshot_download(
    "yoyolicoris/diffvox",
    repo_type="dataset",
    local_dir="./",
    local_files_only=False,
    allow_patterns=["presets/*", "modules/*"],
)


from modules.utils import vec2statedict, get_chunks
from modules.fx import clip_delay_eq_Q, hadamard
from utils import (
    get_log_mags_from_eq,
    chain_functions,
    remove_window_fn,
    jsonparse2hydra,
)
from ito import find_closest_training_sample, one_evaluation
from st_ito.utils import (
    load_param_model,
    get_param_embeds,
    get_feature_embeds,
    load_mfcc_feature_extractor,
    load_mir_feature_extractor,
)

title_md = "# Vocal Effects Style Transfer Demo"
description_md = """
This is a demo of the paper [Improving Inference-Time Optimisation for Vocal Effects Style Transfer with a Gaussian Prior](https://iamycy.github.io/diffvox-ito-demo/), published at WASPAA 2025.
In this demo, you can upload a raw vocal audio file (in mono) and a reference vocal mix (in stereo).
This system will apply vocal effects to the raw vocal such that the processed audio matches the style of the reference mix.

The effects is the same as in [DiffVox](https://huggingface.co/spaces/yoyolicoris/diffvox/), which consists of series of EQ, compressor, delay, and reverb.
We offer four different methods for style transfer:

1. **Mean**: Use the mean of the chosen vocal preset dataset as the effect parameters.
2. **Nearest Neighbour**: Find the closest vocal preset in the chosen dataset based on chosen embedding features, and use its effect parameters.
3. **ST-ITO**: Our proposed method that perform inference-time optimisation in the chosen embedding space, regularised by a Gaussian prior learned from the chosen vocal preset dataset.
4. **Regression**: A pre-trained regression model that directly predicts effect parameters from the reference mix.

### Datasets

- **Internal**: Derived from a proprietary dataset in Sony.
- **MedleyDB**: Derived from solo vocal tracks from the MedleyDB v1/v2 dataset.

### Embedding Models
- **AFx-Rep**: A self-supervised audio representation [model](https://huggingface.co/csteinmetz1/afx-rep) trained on random audio effects.
- **MFCC**: Mel-frequency cepstral coefficients.
- **MIR Features**: A set of common features in MIR like RMS, spectral centroid, spectral flatness, etc.


> **_Note:_** To upload your own audio, click X on the top right corner of the input audio block.
"""

# device = "cpu"
SLIDER_MAX = 3
SLIDER_MIN = -3
NUMBER_OF_PCS = 4
TEMPERATURE = 0.7

CONFIG_PATH = {
    "realtime": "presets/rt_config.yaml",
    "approx": "fx_config.yaml",
}

PRESET_PATH = {
    "internal": Path("presets/internal/"),
    "medleydb": Path("presets/medleydb/"),
}
CKPT_PATH = Path("reg-ckpts/")

PCA_PARAM_FILE = "gaussian.npz"
INFO_PATH = "info.json"
MASK_PATH = "feature_mask.npy"
PARAMS_PATH = "raw_params.npy"
TRAIN_INDEX_PATH = "train_index.npy"
EXAMPLE_PATH = "eleanor_erased.wav"


with open(CONFIG_PATH["approx"]) as fp:
    fx_config = yaml.safe_load(fp)["model"]

with open(CONFIG_PATH["realtime"]) as fp:
    rt_config = yaml.safe_load(fp)["model"]


def load_presets(preset_folder: Path) -> Tensor:
    raw_params = torch.from_numpy(np.load(preset_folder / PARAMS_PATH))
    feature_mask = torch.from_numpy(np.load(preset_folder / MASK_PATH))
    train_index_path = preset_folder / TRAIN_INDEX_PATH
    if train_index_path.exists():
        train_index = torch.from_numpy(np.load(train_index_path))
        raw_params = raw_params[train_index]
    presets = raw_params[:, feature_mask].contiguous()
    return presets


def load_gaussian_params(f: Union[Path, str]) -> Tuple[Tensor, Tensor, Tensor]:
    gauss_params = np.load(f)
    mean = torch.from_numpy(gauss_params["mean"]).float()
    cov = torch.from_numpy(gauss_params["cov"]).float()
    return mean, cov, cov.logdet()


def logp_x(mu, cov, cov_logdet, x):
    diff = x - mu
    b = torch.linalg.solve(cov, diff)
    norm = diff @ b
    assert torch.all(norm >= 0), "Negative norm detected, check covariance matrix."
    return -0.5 * (norm + cov_logdet + mu.shape[0] * math.log(2 * math.pi))


preset_dict = {k: load_presets(v) for k, v in PRESET_PATH.items()}
gaussian_params_dict = {
    k: load_gaussian_params(v / PCA_PARAM_FILE) for k, v in PRESET_PATH.items()
}

# Global latent variable
# z = torch.zeros_like(mean)

with open(PRESET_PATH["internal"] / INFO_PATH) as f:
    info = json.load(f)

param_keys = info["params_keys"]
original_shapes = list(
    map(lambda lst: lst if len(lst) else [1], info["params_original_shapes"])
)

*vec2dict_args, _ = get_chunks(param_keys, original_shapes)
vec2dict_args = [param_keys, original_shapes] + vec2dict_args
vec2dict = partial(
    vec2statedict,
    **dict(
        zip(
            [
                "keys",
                "original_shapes",
                "selected_chunks",
                "position",
                "U_matrix_shape",
            ],
            vec2dict_args,
        )
    ),
)
internal_mean = gaussian_params_dict["internal"][0]

# Global effect
global_fx = instantiate(fx_config)
# global_fx.eval()
global_fx.load_state_dict(vec2dict(internal_mean), strict=False)

ndim_dict = {k: v.ndim for k, v in global_fx.state_dict().items()}
to_fx_state_dict = lambda x: {
    k: v[0] if ndim_dict[k] == 0 else v for k, v in vec2dict(x).items()
}


meter = pyln.Meter(44100)


def get_embedding_model(embedding: str) -> Callable:
    device = environ.get("DEVICE", "cpu")
    match embedding:
        case "afx-rep":
            afx_rep = load_param_model().to(device)
            two_chs_emb_fn = lambda x: get_param_embeds(x, afx_rep, 44100)
        case "mfcc":
            mfcc = load_mfcc_feature_extractor().to(device)
            two_chs_emb_fn = lambda x: get_feature_embeds(x, mfcc)
        case "mir":
            mir = load_mir_feature_extractor().to(device)
            two_chs_emb_fn = lambda x: get_feature_embeds(x, mir)
        case _:
            raise ValueError(f"Unknown encoder: {embedding}")
    return two_chs_emb_fn


def get_regressor() -> Callable:
    with open(CKPT_PATH / "config.yaml") as f:
        config = yaml.safe_load(f)

    model_config = config["model"]

    checkpoints = (CKPT_PATH / "checkpoints").glob("*val_loss*.ckpt")
    lowest_checkpoint = min(checkpoints, key=lambda x: float(x.stem.split("=")[-1]))
    last_ckpt = torch.load(lowest_checkpoint, map_location="cpu")
    model = chain_functions(remove_window_fn, jsonparse2hydra, instantiate)(
        model_config
    )
    model.load_state_dict(last_ckpt["state_dict"])

    device = environ.get("DEVICE", "cpu")
    model = model.to(device)
    model.eval()
    param_stats = torch.load(CKPT_PATH / "param_stats.pt")
    param_mu, param_std = (
        param_stats["mu"].float().to(device),
        param_stats["std"].float().to(device),
    )
    regressor = lambda wet: model(wet, dry=None) * param_std + param_mu
    return regressor


def convert2float(sr: int, x: np.ndarray) -> np.ndarray:
    if sr != 44100:
        x = resample(x, sr, 44100)
    if x.dtype.kind != "f":
        x = x / 32768.0
    if x.ndim == 1:
        x = x[:, None]
    return x


# @spaces.GPU(duration=60)
def inference(
    input_audio,
    ref_audio,
    method,
    dataset,
    embedding,
    mid_side,
    steps,
    prior_weight,
    optimiser,
    lr,
    progress=gr.Progress(track_tqdm=True),
):
    # close all figures to avoid too many open figures
    plt.close("all")

    device = environ.get("DEVICE", "cpu")
    if method == "Mean":
        return gaussian_params_dict[dataset][0].to(device)

    ref = convert2float(*ref_audio)
    ref_loudness = meter.integrated_loudness(ref)
    ref = pyln.normalize.loudness(ref, ref_loudness, -18.0)
    ref = torch.from_numpy(ref).float().T.unsqueeze(0).to(device)

    if method == "Regression":
        regressor = get_regressor()
        with torch.no_grad():
            return regressor(ref).mean(0)

    y = convert2float(*input_audio)
    loudness = meter.integrated_loudness(y)
    y = pyln.normalize.loudness(y, loudness, -18.0)
    y = torch.from_numpy(y).float().T.unsqueeze(0).to(device)

    if y.shape[1] != 1:
        y = y.mean(dim=1, keepdim=True)

    fx = deepcopy(global_fx).to(device)
    fx.train()

    two_chs_emb_fn = chain_functions(
        hadamard if mid_side else lambda x: x,
        get_embedding_model(embedding),
    )

    match method:
        case "Nearest Neighbour":
            vec = find_closest_training_sample(
                fx,
                two_chs_emb_fn,
                to_fx_state_dict,
                preset_dict[dataset].to(device),
                ref,
                y,
                progress,
            )

        case "ST-ITO":
            vec = one_evaluation(
                fx,
                two_chs_emb_fn,
                to_fx_state_dict,
                partial(
                    logp_x, *[x.to(device) for x in gaussian_params_dict["internal"]]
                ),
                internal_mean.to(device),
                ref,
                y,
                optimiser_type=optimiser,
                lr=lr,
                steps=steps,
                weight=prior_weight,
                progress=progress,
            )

        case _:
            raise ValueError(f"Unknown method: {method}")

    return vec


# @spaces.GPU(duration=10)
def render(y, remove_approx, ratio, vec):
    device = environ.get("DEVICE", "cpu")
    y = convert2float(*y)
    loudness = meter.integrated_loudness(y)
    y = pyln.normalize.loudness(y, loudness, -18.0)
    y = torch.from_numpy(y).float().T.unsqueeze(0).to(device)
    if y.shape[1] != 1:
        y = y.mean(dim=1, keepdim=True)

    if remove_approx:
        infer_fx = instantiate(rt_config).to(device)
    else:
        infer_fx = instantiate(fx_config).to(device)

    infer_fx.load_state_dict(vec2dict(vec), strict=False)
    # fx.apply(partial(clip_delay_eq_Q, Q=0.707))
    infer_fx.eval()

    with torch.no_grad():
        direct, wet = infer_fx(y)
    direct = direct.squeeze(0).T.cpu().numpy()
    wet = wet.squeeze(0).T.cpu().numpy()
    angle = ratio * math.pi * 0.5
    test_clipping = direct + wet
    # rendered = fx(y).squeeze(0).T.numpy()
    if np.max(np.abs(test_clipping)) > 1:
        scaler = np.max(np.abs(test_clipping))
        # rendered = rendered / scaler
        direct = direct / scaler
        wet = wet / scaler

    rendered = math.sqrt(2) * (math.cos(angle) * direct + math.sin(angle) * wet)
    return (
        (44100, (rendered * 32768).astype(np.int16)),
        (44100, (direct * 32768).astype(np.int16)),
        (
            44100,
            (wet * 32768).astype(np.int16),
        ),
    )


def model2json(fx):
    fx_names = ["PK1", "PK2", "LS", "HS", "LP", "HP", "DRC"]
    results = {k: v.toJSON() for k, v in zip(fx_names, fx)} | {
        "Panner": fx[7].pan.toJSON()
    }
    spatial_fx = {
        "DLY": fx[7].effects[0].toJSON() | {"LP": fx[7].effects[0].eq.toJSON()},
        "FDN": fx[7].effects[1].toJSON()
        | {
            "Tone correction PEQ": {
                k: v.toJSON() for k, v in zip(fx_names[:4], fx[7].effects[1].eq)
            }
        },
        "Cross Send (dB)": fx[7].params.sends_0.log10().mul(20).item(),
    }
    return {
        "Direct": results,
        "Sends": spatial_fx,
    }


@torch.no_grad()
def plot_eq(fx):
    fig, ax = plt.subplots(figsize=(6, 4), constrained_layout=True)
    w, eq_log_mags = get_log_mags_from_eq(fx[:6])
    ax.plot(w, sum(eq_log_mags), color="black", linestyle="-")
    for i, eq_log_mag in enumerate(eq_log_mags):
        ax.plot(w, eq_log_mag, "k-", alpha=0.3)
        ax.fill_between(w, eq_log_mag, 0, facecolor="gray", edgecolor="none", alpha=0.1)
    ax.set_xlabel("Frequency (Hz)")
    ax.set_ylabel("Magnitude (dB)")
    ax.set_xlim(20, 20000)
    ax.set_ylim(-40, 20)
    ax.set_xscale("log")
    ax.grid()
    return fig


@torch.no_grad()
def plot_comp(fx):
    fig, ax = plt.subplots(figsize=(6, 5), constrained_layout=True)
    comp = fx[6]
    cmp_th = comp.params.cmp_th.item()
    exp_th = comp.params.exp_th.item()
    cmp_ratio = comp.params.cmp_ratio.item()
    exp_ratio = comp.params.exp_ratio.item()
    make_up = comp.params.make_up.item()
    # print(cmp_ratio, cmp_th, exp_ratio, exp_th, make_up)

    comp_in = np.linspace(-80, 0, 100)
    comp_curve = np.where(
        comp_in > cmp_th,
        comp_in - (comp_in - cmp_th) * (cmp_ratio - 1) / cmp_ratio,
        comp_in,
    )
    comp_out = (
        np.where(
            comp_curve < exp_th,
            comp_curve - (exp_th - comp_curve) / exp_ratio,
            comp_curve,
        )
        + make_up
    )
    ax.plot(comp_in, comp_out, c="black", linestyle="-")
    ax.plot(comp_in, comp_in, c="r", alpha=0.5)
    ax.set_xlabel("Input Level (dB)")
    ax.set_ylabel("Output Level (dB)")
    ax.set_xlim(-80, 0)
    ax.set_ylim(-80, 0)
    ax.grid()
    return fig


@torch.no_grad()
def plot_delay(fx):
    fig, ax = plt.subplots(figsize=(6, 4), constrained_layout=True)
    delay = fx[7].effects[0]
    w, eq_log_mags = get_log_mags_from_eq([delay.eq])
    log_gain = delay.params.gain.log10().item() * 20
    d = delay.params.delay.item() / 1000
    log_mag = sum(eq_log_mags)
    ax.plot(w, log_mag + log_gain, color="black", linestyle="-")

    log_feedback = delay.params.feedback.log10().item() * 20
    for i in range(1, 10):
        feedback_log_mag = log_mag * (i + 1) + log_feedback * i + log_gain
        ax.plot(
            w,
            feedback_log_mag,
            c="black",
            alpha=max(0, (10 - i * d * 4) / 10),
            linestyle="-",
        )

    ax.set_xscale("log")
    ax.set_xlim(20, 20000)
    ax.set_ylim(-80, 0)
    ax.set_xlabel("Frequency (Hz)")
    ax.set_ylabel("Magnitude (dB)")
    ax.grid()
    return fig


@torch.no_grad()
def plot_reverb(fx):
    fig, ax = plt.subplots(figsize=(6, 4), constrained_layout=True)
    fdn = fx[7].effects[1]
    w, eq_log_mags = get_log_mags_from_eq(fdn.eq)

    bc = fdn.params.c.norm() * fdn.params.b.norm()
    log_bc = torch.log10(bc).item() * 20
    # eq_log_mags = [x + log_bc / len(eq_log_mags) for x in eq_log_mags]
    # ax.plot(w, sum(eq_log_mags), color="black", linestyle="-")
    eq_log_mags = sum(eq_log_mags) + log_bc
    ax.plot(w, eq_log_mags, color="black", linestyle="-")

    ax.set_xlabel("Frequency (Hz)")
    ax.set_ylabel("Magnitude (dB)")
    ax.set_xlim(20, 20000)
    ax.set_ylim(-40, 20)
    ax.set_xscale("log")
    ax.grid()
    return fig


@torch.no_grad()
def plot_t60(fx):
    fig, ax = plt.subplots(figsize=(6, 4), constrained_layout=True)
    fdn = fx[7].effects[1]
    gamma = fdn.params.gamma.squeeze().numpy()
    delays = fdn.delays.numpy()
    w = np.linspace(0, 22050, gamma.size)
    t60 = -60 / (20 * np.log10(gamma + 1e-10) / np.min(delays)) / 44100
    ax.plot(w, t60, color="black", linestyle="-")
    ax.set_xlabel("Frequency (Hz)")
    ax.set_ylabel("T60 (s)")
    ax.set_xlim(20, 20000)
    ax.set_ylim(0, 9)
    ax.set_xscale("log")
    ax.grid()
    return fig


def vec2fx(x):
    fx = deepcopy(global_fx)
    fx.load_state_dict(vec2dict(x), strict=False)
    # fx.apply(partial(clip_delay_eq_Q, Q=0.707))
    return fx


with gr.Blocks() as demo:
    fx_params = gr.State(internal_mean)
    # fx = vec2fx(fx_params.value)
    # sr, y = read(EXAMPLE_PATH)

    default_audio_block = partial(gr.Audio, type="numpy", loop=True)

    gr.Markdown(
        title_md,
        elem_id="title",
    )
    with gr.Row():
        gr.Markdown(
            description_md,
            elem_id="description",
        )
        gr.Image("overview.png", elem_id="diagram", height=500)

    with gr.Row():
        with gr.Column():
            audio_input = default_audio_block(
                sources="upload",
                label="Input Audio",
                # value=(sr, y)
            )
            audio_reference = default_audio_block(
                sources="upload",
                label="Reference Audio",
            )
            with gr.Row():
                method_dropdown = gr.Dropdown(
                    ["Mean", "Nearest Neighbour", "ST-ITO", "Regression"],
                    value="ST-ITO",
                    label=f"Style Transfer Method",
                    interactive=True,
                )
                process_button = gr.Button(
                    "Run", elem_id="render-button", variant="primary"
                )

        with gr.Column():
            audio_output = default_audio_block(label="Output Audio", interactive=False)
            dry_wet_ratio = gr.Slider(
                minimum=0,
                maximum=1,
                value=0.5,
                label="Dry/Wet Ratio",
                interactive=True,
            )
            direct_output = default_audio_block(label="Direct Audio", interactive=False)
            wet_output = default_audio_block(label="Wet Audio", interactive=False)

    with gr.Row():
        with gr.Column():
            _ = gr.Markdown("## Control Parameters")

            with gr.Row():
                dataset_dropdown = gr.Dropdown(
                    [("Internal", "internal"), ("MedleyDB", "medleydb")],
                    label="Prior Distribution (Dataset)",
                    info="This parameter has no effect when using the ST-ITO and Regression methods.",
                    value="internal",
                    interactive=True,
                )
                embedding_dropdown = gr.Dropdown(
                    [("AFx-Rep", "afx-rep"), ("MFCC", "mfcc"), ("MIR Features", "mir")],
                    label="Embedding Model",
                    info="This parameter has no effect when using the Mean and Regression methods.",
                    value="afx-rep",
                    interactive=True,
                )
                # with gr.Column():
                remove_approx_checkbox = gr.Checkbox(
                    label="Use Real-time Effects",
                    info="Use real-time delay and reverb effects instead of approximated ones.",
                    value=False,
                    interactive=True,
                )
                mid_side_checkbox = gr.Checkbox(
                    label="Use Mid-Side Processing",
                    info="This option has no effect when using the Mean and Regression methods.",
                    value=True,
                    interactive=True,
                )

        with gr.Column():
            _ = gr.Markdown("## Parameters for ST-ITO Method")
            with gr.Row():
                optimisation_steps = gr.Slider(
                    minimum=1,
                    maximum=2000,
                    value=100,
                    step=1,
                    label="Number of Optimisation Steps",
                    interactive=True,
                )
                prior_weight = gr.Dropdown(
                    [
                        ("0", 0.0),
                        ("0.001", 0.001),
                        ("0.01", 0.01),
                        ("0.1", 0.1),
                        ("1", 1.0),
                    ],
                    info="Weight of the prior distribution in the loss function. A higher value means the model will try to stay closer to the prior distribution.",
                    value=0.01,
                    label="Prior Weight",
                    interactive=True,
                )
                optimiser_dropdown = gr.Dropdown(
                    [
                        "Adadelta",
                        "Adafactor",
                        "Adagrad",
                        "Adam",
                        "AdamW",
                        "Adamax",
                        "RMSprop",
                        "ASGD",
                        "NAdam",
                        "RAdam",
                        "SGD",
                    ],
                    value="Adam",
                    label="Optimiser",
                    interactive=True,
                )
                lr_slider = gr.Dropdown(
                    [("0.0001", 1e-4), ("0.001", 1e-3), ("0.01", 1e-2), ("0.1", 1e-1)],
                    value=1e-2,
                    label="Learning Rate",
                    interactive=True,
                )

    _ = gr.Markdown("## Effect Parameters Visualisation")
    with gr.Row():
        peq_plot = gr.Plot(
            plot_eq(global_fx), label="PEQ Frequency Response", elem_id="peq-plot"
        )
        comp_plot = gr.Plot(
            plot_comp(global_fx), label="Compressor Curve", elem_id="comp-plot"
        )

    with gr.Row():
        delay_plot = gr.Plot(
            plot_delay(global_fx),
            label="Delay Frequency Response",
            elem_id="delay-plot",
        )
        reverb_plot = gr.Plot(
            plot_reverb(global_fx),
            label="Tone Correction PEQ",
            elem_id="reverb-plot",
            min_width=160,
        )
        t60_plot = gr.Plot(
            plot_t60(global_fx), label="Decay Time", elem_id="t60-plot", min_width=160
        )

    _ = gr.Markdown("## Effect Settings JSON")
    with gr.Row():
        json_output = gr.JSON(
            model2json(global_fx), label="Effect Settings", max_height=800, open=True
        )

    process_button.click(
        spaces.GPU(duration=60)(
            chain_functions(
                lambda audio, approx, ratio, *args: (
                    audio,
                    approx,
                    ratio,
                    inference(audio, *args),
                ),
                lambda audio, approx, ratio, vec: (
                    vec2fx(vec),
                    *render(audio, approx, ratio, vec),
                    vec,
                ),
                lambda fx, *args: (
                    *args,
                    *map(
                        lambda f: f(fx),
                        [
                            plot_eq,
                            plot_comp,
                            plot_delay,
                            plot_reverb,
                            plot_t60,
                            model2json,
                        ],
                    ),
                ),
                lambda out, dir, wet, vec, *args: (
                    out,
                    dir,
                    wet,
                    vec.cpu(),
                    *args,
                ),
            )
        ),
        inputs=[
            audio_input,
            remove_approx_checkbox,
            dry_wet_ratio,
            audio_reference,
            method_dropdown,
            dataset_dropdown,
            embedding_dropdown,
            mid_side_checkbox,
            optimisation_steps,
            prior_weight,
            optimiser_dropdown,
            lr_slider,
        ],
        outputs=[
            audio_output,
            direct_output,
            wet_output,
            fx_params,
            peq_plot,
            comp_plot,
            delay_plot,
            reverb_plot,
            t60_plot,
            json_output,
        ],
    )

    remove_approx_checkbox.change(
        spaces.GPU(duration=10)(
            lambda in_audio, out_audio, di, wet, *args: (
                (out_audio, di, wet) if in_audio is None else render(in_audio, *args)
            )
        ),
        inputs=[
            audio_input,
            audio_output,
            direct_output,
            wet_output,
            remove_approx_checkbox,
            dry_wet_ratio,
            fx_params,
        ],
        outputs=[
            audio_output,
            direct_output,
            wet_output,
        ],
    )

    dry_wet_ratio.input(
        chain_functions(
            lambda _, *args: (_, *map(lambda x: x[1] / 32768, args)),
            lambda ratio, d, w: math.sqrt(2)
            * (
                math.cos(ratio * math.pi * 0.5) * d
                + math.sin(ratio * math.pi * 0.5) * w
            ),
            lambda x: (44100, (x * 32768).astype(np.int16)),
        ),
        inputs=[dry_wet_ratio, direct_output, wet_output],
        outputs=[audio_output],
    )


demo.launch()