audio.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import os
  2. from functools import lru_cache
  3. from typing import Union
  4. import ffmpeg
  5. import numpy as np
  6. import torch
  7. import torch.nn.functional as F
  8. from .utils import exact_div
  9. # hard-coded audio hyperparameters
  10. SAMPLE_RATE = 16000
  11. N_FFT = 400
  12. N_MELS = 80
  13. HOP_LENGTH = 160
  14. CHUNK_LENGTH = 30
  15. N_SAMPLES = CHUNK_LENGTH * SAMPLE_RATE # 480000: number of samples in a chunk
  16. N_FRAMES = exact_div(
  17. N_SAMPLES, HOP_LENGTH
  18. ) # 3000: number of frames in a mel spectrogram input
  19. N_SAMPLES_PER_TOKEN = HOP_LENGTH * 2 # the initial convolutions has stride 2
  20. FRAMES_PER_SECOND = exact_div(SAMPLE_RATE, HOP_LENGTH) # 10ms per audio frame
  21. TOKENS_PER_SECOND = exact_div(SAMPLE_RATE, N_SAMPLES_PER_TOKEN) # 20ms per audio token
  22. def load_audio(file: str, sr: int = SAMPLE_RATE):
  23. """
  24. Open an audio file and read as mono waveform, resampling as necessary
  25. Parameters
  26. ----------
  27. file: str
  28. The audio file to open
  29. sr: int
  30. The sample rate to resample the audio if necessary
  31. Returns
  32. -------
  33. A NumPy array containing the audio waveform, in float32 dtype.
  34. """
  35. try:
  36. # This launches a subprocess to decode audio while down-mixing and resampling as necessary.
  37. # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed.
  38. out, _ = (
  39. ffmpeg.input(file, threads=0)
  40. .output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sr)
  41. .run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
  42. )
  43. except ffmpeg.Error as e:
  44. raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
  45. return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0
  46. def pad_or_trim(array, length: int = N_SAMPLES, *, axis: int = -1):
  47. """
  48. Pad or trim the audio array to N_SAMPLES, as expected by the encoder.
  49. """
  50. if torch.is_tensor(array):
  51. if array.shape[axis] > length:
  52. array = array.index_select(
  53. dim=axis, index=torch.arange(length, device=array.device)
  54. )
  55. if array.shape[axis] < length:
  56. pad_widths = [(0, 0)] * array.ndim
  57. pad_widths[axis] = (0, length - array.shape[axis])
  58. array = F.pad(array, [pad for sizes in pad_widths[::-1] for pad in sizes])
  59. else:
  60. if array.shape[axis] > length:
  61. array = array.take(indices=range(length), axis=axis)
  62. if array.shape[axis] < length:
  63. pad_widths = [(0, 0)] * array.ndim
  64. pad_widths[axis] = (0, length - array.shape[axis])
  65. array = np.pad(array, pad_widths)
  66. return array
  67. @lru_cache(maxsize=None)
  68. def mel_filters(device, n_mels: int = N_MELS) -> torch.Tensor:
  69. """
  70. load the mel filterbank matrix for projecting STFT into a Mel spectrogram.
  71. Allows decoupling librosa dependency; saved using:
  72. np.savez_compressed(
  73. "mel_filters.npz",
  74. mel_80=librosa.filters.mel(sr=16000, n_fft=400, n_mels=80),
  75. )
  76. """
  77. assert n_mels == 80, f"Unsupported n_mels: {n_mels}"
  78. with np.load(
  79. os.path.join(os.path.dirname(__file__), "assets", "mel_filters.npz")
  80. ) as f:
  81. return torch.from_numpy(f[f"mel_{n_mels}"]).to(device)
  82. def log_mel_spectrogram(
  83. audio: Union[str, np.ndarray, torch.Tensor], n_mels: int = N_MELS
  84. ):
  85. """
  86. Compute the log-Mel spectrogram of
  87. Parameters
  88. ----------
  89. audio: Union[str, np.ndarray, torch.Tensor], shape = (*)
  90. The path to audio or either a NumPy array or Tensor containing the audio waveform in 16 kHz
  91. n_mels: int
  92. The number of Mel-frequency filters, only 80 is supported
  93. Returns
  94. -------
  95. torch.Tensor, shape = (80, n_frames)
  96. A Tensor that contains the Mel spectrogram
  97. """
  98. if not torch.is_tensor(audio):
  99. if isinstance(audio, str):
  100. audio = load_audio(audio)
  101. audio = torch.from_numpy(audio)
  102. window = torch.hann_window(N_FFT).to(audio.device)
  103. stft = torch.stft(audio, N_FFT, HOP_LENGTH, window=window, return_complex=True)
  104. magnitudes = stft[..., :-1].abs() ** 2
  105. filters = mel_filters(audio.device, n_mels)
  106. mel_spec = filters @ magnitudes
  107. log_spec = torch.clamp(mel_spec, min=1e-10).log10()
  108. log_spec = torch.maximum(log_spec, log_spec.max() - 8.0)
  109. log_spec = (log_spec + 4.0) / 4.0
  110. return log_spec