File size: 9,533 Bytes
93cf757
1e7ab6c
c8dbfb3
0f79c5b
d446ca4
 
 
42843b6
93cf757
1e7ab6c
d446ca4
e20c50f
c8dbfb3
 
e20c50f
0f79c5b
 
93cf757
4674b6c
d446ca4
e7bb95d
0f79c5b
4674b6c
d446ca4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0f79c5b
 
 
 
df38a50
4f235e3
4cf88e6
df38a50
d446ca4
 
 
 
 
4cf88e6
0f79c5b
a299dfc
 
4cf88e6
a299dfc
d446ca4
 
a52c38e
c8dbfb3
 
 
 
 
 
e7bb95d
c8dbfb3
 
0b334e9
c8dbfb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6df9060
6b3c03e
4cf88e6
6b3c03e
4cf88e6
 
 
4f235e3
e7bb95d
 
 
 
6df9060
c8dbfb3
 
 
4f235e3
 
 
 
 
 
e20c50f
4cf88e6
e2efa2c
 
 
e20c50f
d446ca4
e20c50f
0f79c5b
e20c50f
1e7ab6c
 
 
e2efa2c
 
 
e88b7ef
1e7ab6c
 
 
 
e20c50f
1e7ab6c
9240be0
1e7ab6c
9240be0
1e7ab6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30cd35c
1e7ab6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e20c50f
1e7ab6c
 
 
 
 
 
d446ca4
 
 
 
1e7ab6c
0b334e9
1e7ab6c
0b334e9
1e7ab6c
 
 
 
 
 
d446ca4
d619a71
1e7ab6c
d619a71
5e58c6e
d446ca4
 
1e7ab6c
ec1b175
bd0f589
1e7ab6c
 
 
 
ec1b175
bd0f589
1e7ab6c
 
 
d446ca4
 
 
1e7ab6c
d446ca4
1e7ab6c
d446ca4
e20c50f
d446ca4
a52c38e
1e7ab6c
a52c38e
 
 
 
1e7ab6c
 
42843b6
d446ca4
4cf88e6
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
import math
import tempfile
from typing import Optional, Tuple, Union

import gradio
import gradio.inputs
import gradio.outputs
import markdown
import matplotlib.pyplot as plt
import numpy as np
import torch
from loguru import logger
from torch import Tensor
from torchaudio.backend.common import AudioMetaData

from df import config
from df.enhance import enhance, init_df, load_audio, save_audio
from df.utils import resample

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model, df, _ = init_df(config_allow_defaults=True)
model = model.to(device=device).eval()


def mix_at_snr(clean, noise, snr, eps=1e-10):
    """Mix clean and noise signal at a given SNR.

    Args:
        clean: 1D Tensor with the clean signal to mix.
        noise: 1D Tensor of shape.
        snr: Signal to noise ratio.

    Returns:
        clean: 1D Tensor with gain changed according to the snr.
        noise: 1D Tensor with the combined noise channels.
        mix: 1D Tensor with added clean and noise signals.

    """
    clean = torch.as_tensor(clean).mean(0, keepdim=True)
    noise = torch.as_tensor(noise).mean(0, keepdim=True)
    if noise.shape[1] < clean.shape[1]:
        noise = noise.repeat((1, int(math.ceil(clean.shape[1] / noise.shape[1]))))
    max_start = int(noise.shape[1] - clean.shape[1])
    start = torch.randint(0, max_start, ()).item() if max_start > 0 else 0
    logger.debug(f"start: {start}, {clean.shape}")
    noise = noise[:, start : start + clean.shape[1]]
    E_speech = torch.mean(clean.pow(2)) + eps
    E_noise = torch.mean(noise.pow(2))
    K = torch.sqrt((E_noise / E_speech) * 10 ** (snr / 10) + eps)
    noise = noise / K
    mixture = clean + noise
    logger.debug("mixture: {mixture.shape}")
    assert torch.isfinite(mixture).all()
    max_m = mixture.abs().max()
    if max_m > 1:
        logger.warning(f"Clipping detected during mixing. Reducing gain by {1/max_m}")
        clean, noise, mixture = clean / max_m, noise / max_m, mixture / max_m
    return clean, noise, mixture


def load_audio_gradio(
    audio_or_file: Union[None, str, Tuple[int, np.ndarray]], sr: int
) -> Optional[Tuple[Tensor, AudioMetaData]]:
    if audio_or_file is None:
        return None
    if isinstance(audio_or_file, str):
        if audio_or_file.lower() == "none":
            return None
        # First try default format
        audio, meta = load_audio(audio_or_file, sr)
    else:
        meta = AudioMetaData(-1, -1, -1, -1, "")
        assert isinstance(audio_or_file, (tuple, list))
        meta.sample_rate, audio_np = audio_or_file
        # Gradio documentation says, the shape is [samples, 2], but apparently sometimes its not.
        audio_np = audio_np.reshape(audio_np.shape[0], -1).T
        if audio_np.dtype == np.int16:
            audio_np = (audio_np / (1 << 15)).astype(np.float32)
        elif audio_np.dtype == np.int32:
            audio_np = (audio_np / (1 << 31)).astype(np.float32)
        audio = resample(torch.from_numpy(audio_np), meta.sample_rate, sr)
    return audio, meta


def mix_and_denoise(
    speech_rec: Union[str, Tuple[int, np.ndarray]], speech_upl: str, noise_fn: str, snr: int
):
    sr = config("sr", 48000, int, section="df")
    logger.info(
        f"Got parameters speech_rec: {speech_rec}, speech_upl: {speech_upl}, noise: {noise_fn}, snr: {snr}"
    )
    if noise_fn is None:
        noise_fn = "samples/dkitchen.wav"
    meta = AudioMetaData(-1, -1, -1, -1, "")
    max_s = 10  # limit to 10 seconds
    if speech_rec is None and speech_upl is None:
        speech, meta = load_audio("samples/p232_013_clean.wav", sr)
    elif speech_upl is not None:
        speech, meta = load_audio(speech_upl, sr)
    else:
        tmp = load_audio_gradio(speech_rec, sr)
        assert tmp is not None
        speech, meta = tmp
    if speech.dim() > 1 and speech.shape[0] > 1:
        assert (
            speech.shape[1] > speech.shape[0]
        ), f"Expecting channels first, but got {speech.shape}"
        speech = speech.mean(dim=0, keepdim=True)
        speech = speech[..., : max_s * sr]
    logger.info(f"Loaded speech with shape {speech.shape}")
    noise, _ = load_audio(noise_fn, sr)  # type: ignore
    if meta.sample_rate != sr:
        # Low pass filter by resampling
        noise = resample(resample(noise, sr, meta.sample_rate), meta.sample_rate, sr)
    logger.info(f"Loaded noise with shape {noise.shape}")
    speech, noise, noisy = mix_at_snr(speech, noise, snr)
    logger.info("Start denoising audio")
    enhanced = enhance(model, df, noisy)
    logger.info("Denoising finished")
    lim = torch.linspace(0.0, 1.0, int(sr * 0.15)).unsqueeze(0)
    lim = torch.cat((lim, torch.ones(1, enhanced.shape[1] - lim.shape[1])), dim=1)
    enhanced = enhanced * lim
    if meta.sample_rate != sr:
        enhanced = resample(enhanced, sr, meta.sample_rate)
        noisy = resample(noisy, sr, meta.sample_rate)
        sr = meta.sample_rate
    noisy_fn = tempfile.NamedTemporaryFile(suffix="noisy.wav", delete=False).name
    save_audio(noisy_fn, noisy, sr)
    enhanced_fn = tempfile.NamedTemporaryFile(suffix="enhanced.wav", delete=False).name
    save_audio(enhanced_fn, enhanced, sr)
    logger.info(f"saved audios: {noisy_fn}, {enhanced_fn}")
    return (
        noisy_fn,
        spec_figure(noisy, sr=sr),
        enhanced_fn,
        spec_figure(enhanced, sr=sr),
    )


def specshow(
    spec,
    ax=None,
    title=None,
    xlabel=None,
    ylabel=None,
    sr=48000,
    n_fft=None,
    hop=None,
    t=None,
    f=None,
    vmin=-100,
    vmax=0,
    xlim=None,
    ylim=None,
    cmap="inferno",
):
    """Plots a spectrogram of shape [F, T]"""
    spec_np = spec.cpu().numpy() if isinstance(spec, torch.Tensor) else spec
    if ax is not None:
        set_title = ax.set_title
        set_xlabel = ax.set_xlabel
        set_ylabel = ax.set_ylabel
        set_xlim = ax.set_xlim
        set_ylim = ax.set_ylim
    else:
        ax = plt
        set_title = plt.title
        set_xlabel = plt.xlabel
        set_ylabel = plt.ylabel
        set_xlim = plt.xlim
        set_ylim = plt.ylim
    if n_fft is None:
        if spec.shape[0] % 2 == 0:
            n_fft = spec.shape[0] * 2
        else:
            n_fft = (spec.shape[0] - 1) * 2
    hop = hop or n_fft // 4
    if t is None:
        t = np.arange(0, spec_np.shape[-1]) * hop / sr
    if f is None:
        f = np.arange(0, spec_np.shape[0]) * sr // 2 / (n_fft // 2) / 1000
    im = ax.pcolormesh(
        t, f, spec_np, rasterized=True, shading="auto", vmin=vmin, vmax=vmax, cmap=cmap
    )
    if title is not None:
        set_title(title)
    if xlabel is not None:
        set_xlabel(xlabel)
    if ylabel is not None:
        set_ylabel(ylabel)
    if xlim is not None:
        set_xlim(xlim)
    if ylim is not None:
        set_ylim(ylim)
    return im


def spec_figure(
    audio: torch.Tensor,
    figsize=(15, 5),
    colorbar=False,
    colorbar_format=None,
    figure=None,
    return_im=False,
    labels=True,
    **kwargs,
) -> plt.Figure:
    audio = torch.as_tensor(audio)
    if labels:
        kwargs.setdefault("xlabel", "Time [s]")
        kwargs.setdefault("ylabel", "Frequency [Hz]")
    n_fft = kwargs.setdefault("n_fft", 1024)
    hop = kwargs.setdefault("hop", 512)
    w = torch.hann_window(n_fft, device=audio.device)
    spec = torch.stft(audio, n_fft, hop, window=w, return_complex=False)
    spec = spec.div_(w.pow(2).sum())
    spec = torch.view_as_complex(spec).abs().clamp_min(1e-12).log10().mul(10)
    kwargs.setdefault("vmax", max(0.0, spec.max().item()))

    if figure is None:
        figure = plt.figure(figsize=figsize)
        figure.set_tight_layout(True)
    if spec.dim() > 2:
        spec = spec.squeeze(0)
    im = specshow(spec, **kwargs)
    if colorbar:
        ckwargs = {}
        if "ax" in kwargs:
            if colorbar_format is None:
                if kwargs.get("vmin", None) is not None or kwargs.get("vmax", None) is not None:
                    colorbar_format = "%+2.0f dB"
            ckwargs = {"ax": kwargs["ax"]}
        plt.colorbar(im, format=colorbar_format, **ckwargs)
    if return_im:
        return im
    return figure


inputs = [
    gradio.inputs.Audio(
        source="microphone",
        type="numpy",
        optional=True,
        label="Record your own voice",
    ),
    gradio.inputs.Audio(
        source="upload",
        type="filepath",
        optional=True,
        label="Alternative: Upload speech sample",
    ),
    gradio.inputs.Audio(
        source="upload", type="filepath", optional=True, label="Upload noise sample"
    ),
    gradio.inputs.Slider(minimum=-10, maximum=40, step=5, default=10),  # SNR
]
examples = [
    [
        "none",
        "samples/p232_013_clean.wav",
        "samples/dkitchen.wav",
        10,
    ],
    [
        "none",
        "samples/p232_019_clean.wav",
        "samples/dliving.wav",
        10,
    ],
]
outputs = [
    gradio.outputs.Audio(label="Noisy"),
    gradio.outputs.Image(type="plot"),
    gradio.outputs.Audio(label="Enhanced"),
    gradio.outputs.Image(type="plot"),
]
description = "This demo denoises audio files using DeepFilterNet. Try it with your own voice!"
iface = gradio.Interface(
    fn=mix_and_denoise,
    title="DeepFilterNet Demo",
    inputs=inputs,
    outputs=outputs,
    examples=examples,
    description=description,
    layout="horizontal",
    allow_flagging="never",
    article=markdown.markdown(open("usage.md").read()),
)
iface.launch(cache_examples=False, debug=True)