denoiser.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import sys
  2. sys.path.append('tacotron2')
  3. import torch
  4. from layers import STFT
  5. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  6. class Denoiser(torch.nn.Module):
  7. """ Removes model bias from audio produced with waveglow """
  8. def __init__(self, waveglow, filter_length=1024, n_overlap=4,
  9. win_length=1024, mode='zeros'):
  10. super(Denoiser, self).__init__()
  11. self.stft = STFT(filter_length=filter_length,
  12. hop_length=int(filter_length/n_overlap),
  13. win_length=win_length).to(device)
  14. if mode == 'zeros':
  15. mel_input = torch.zeros(
  16. (1, 80, 88),
  17. dtype=waveglow.upsample.weight.dtype,
  18. device=waveglow.upsample.weight.device)
  19. elif mode == 'normal':
  20. mel_input = torch.randn(
  21. (1, 80, 88),
  22. dtype=waveglow.upsample.weight.dtype,
  23. device=waveglow.upsample.weight.device)
  24. else:
  25. raise Exception("Mode {} if not supported".format(mode))
  26. with torch.no_grad():
  27. bias_audio = waveglow.infer(mel_input, sigma=0.0).float()
  28. bias_spec, _ = self.stft.transform(bias_audio)
  29. self.register_buffer('bias_spec', bias_spec[:, :, 0][:, :, None])
  30. def forward(self, audio, strength=0.1):
  31. # audio_spec, audio_angles = self.stft.transform(audio.cuda().float())
  32. audio_spec, audio_angles = self.stft.transform(audio.float())
  33. audio_spec_denoised = audio_spec - self.bias_spec * strength
  34. audio_spec_denoised = torch.clamp(audio_spec_denoised, 0.0)
  35. audio_denoised = self.stft.inverse(audio_spec_denoised, audio_angles)
  36. return audio_denoised