Fork of https://github.com/alokprasad/fastspeech_squeezewave to also fix denoising in squeezewave
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

147 lines
6.0 KiB

  1. """
  2. We retain the copyright notice from the original author. However, we reserve
  3. our rights on the modifications based on the original code.
  4. BSD 3-Clause License
  5. Copyright (c) 2017, Prem Seetharaman
  6. All rights reserved.
  7. * Redistribution and use in source and binary forms, with or without
  8. modification, are permitted provided that the following conditions are met:
  9. * Redistributions of source code must retain the above copyright notice,
  10. this list of conditions and the following disclaimer.
  11. * Redistributions in binary form must reproduce the above copyright notice, this
  12. list of conditions and the following disclaimer in the
  13. documentation and/or other materials provided with the distribution.
  14. * Neither the name of the copyright holder nor the names of its
  15. contributors may be used to endorse or promote products derived from this
  16. software without specific prior written permission.
  17. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  18. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  19. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  21. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  22. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  23. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  24. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  26. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. """
  28. import torch
  29. import numpy as np
  30. import torch.nn.functional as F
  31. from torch.autograd import Variable
  32. from scipy.signal import get_window
  33. from librosa.util import pad_center, tiny
  34. from audio_processing import window_sumsquare
  35. class STFT(torch.nn.Module):
  36. """adapted from Prem Seetharaman's https://github.com/pseeth/pytorch-stft"""
  37. def __init__(self, filter_length=800, hop_length=200, win_length=800,
  38. window='hann', n_group=256):
  39. super(STFT, self).__init__()
  40. self.filter_length = filter_length
  41. self.hop_length = hop_length
  42. self.win_length = win_length
  43. self.window = window
  44. self.forward_transform = None
  45. self.n_group = n_group
  46. scale = self.filter_length / self.hop_length
  47. fourier_basis = np.fft.fft(np.eye(self.filter_length))
  48. cutoff = int((self.filter_length / 2 + 1))
  49. fourier_basis = np.vstack([np.real(fourier_basis[:cutoff, :]),
  50. np.imag(fourier_basis[:cutoff, :])])
  51. forward_basis = torch.FloatTensor(fourier_basis[:, None, :])
  52. inverse_basis = torch.FloatTensor(
  53. np.linalg.pinv(scale * fourier_basis).T[:, None, :])
  54. if window is not None:
  55. assert(win_length >= filter_length)
  56. # get window and zero center pad it to filter_length
  57. fft_window = get_window(window, win_length, fftbins=True)
  58. fft_window = pad_center(fft_window, filter_length)
  59. fft_window = torch.from_numpy(fft_window).float()
  60. # window the bases
  61. forward_basis *= fft_window
  62. inverse_basis *= fft_window
  63. self.register_buffer('forward_basis', forward_basis.float())
  64. self.register_buffer('inverse_basis', inverse_basis.float())
  65. def transform(self, input_data):
  66. num_batches = input_data.size(0)
  67. num_samples = input_data.size(1)
  68. self.num_samples = num_samples
  69. # similar to librosa, reflect-pad the input
  70. input_data = input_data.view(num_batches, 1, num_samples)
  71. pad = ((64 - 1) * self.hop_length + self.filter_length - num_samples) // 2
  72. if pad < 0:
  73. pad = self.filter_length // 2
  74. input_data = F.pad(
  75. input_data.unsqueeze(1),
  76. (int(pad), int(pad), 0, 0),
  77. mode='reflect')
  78. input_data = input_data.squeeze(1)
  79. forward_transform = F.conv1d(
  80. input_data,
  81. Variable(self.forward_basis, requires_grad=False),
  82. stride=self.hop_length,
  83. padding=0)
  84. cutoff = int((self.filter_length / 2) + 1)
  85. real_part = forward_transform[:, :cutoff, :]
  86. imag_part = forward_transform[:, cutoff:, :]
  87. magnitude = torch.sqrt(real_part**2 + imag_part**2)
  88. phase = torch.autograd.Variable(
  89. torch.atan2(imag_part.data, real_part.data))
  90. return magnitude, phase
  91. def inverse(self, magnitude, phase):
  92. recombine_magnitude_phase = torch.cat(
  93. [magnitude*torch.cos(phase), magnitude*torch.sin(phase)], dim=1)
  94. inverse_transform = F.conv_transpose1d(
  95. recombine_magnitude_phase,
  96. Variable(self.inverse_basis, requires_grad=False),
  97. stride=self.hop_length,
  98. padding=0)
  99. if self.window is not None:
  100. window_sum = window_sumsquare(
  101. self.window, magnitude.size(-1), hop_length=self.hop_length,
  102. win_length=self.win_length, n_fft=self.filter_length,
  103. dtype=np.float32)
  104. # remove modulation effects
  105. approx_nonzero_indices = torch.from_numpy(
  106. np.where(window_sum > tiny(window_sum))[0])
  107. window_sum = torch.autograd.Variable(
  108. torch.from_numpy(window_sum), requires_grad=False)
  109. inverse_transform[:, :, approx_nonzero_indices] /= window_sum[approx_nonzero_indices]
  110. # scale by hop ratio
  111. inverse_transform *= float(self.filter_length) / self.hop_length
  112. inverse_transform = inverse_transform[:, :, int(self.filter_length/2):]
  113. inverse_transform = inverse_transform[:, :, :-int(self.filter_length/2):]
  114. return inverse_transform
  115. def forward(self, input_data):
  116. self.magnitude, self.phase = self.transform(input_data)
  117. reconstruction = self.inverse(self.magnitude, self.phase)
  118. return reconstruction