dnsmos.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. # Copyright The Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. from functools import lru_cache
  16. from typing import Any, Optional
  17. import numpy as np
  18. import torch
  19. from torch import Tensor
  20. from torchmetrics.utilities import rank_zero_info, rank_zero_warn
  21. from torchmetrics.utilities.imports import _LIBROSA_AVAILABLE, _ONNXRUNTIME_AVAILABLE, _REQUESTS_AVAILABLE
  22. if _LIBROSA_AVAILABLE and _ONNXRUNTIME_AVAILABLE and _REQUESTS_AVAILABLE:
  23. import librosa
  24. import onnxruntime as ort
  25. import requests
  26. from onnxruntime import InferenceSession
  27. else:
  28. librosa, ort, requests = None, None, None # type:ignore
  29. class InferenceSession: # type:ignore
  30. """Dummy InferenceSession."""
  31. def __init__(self, **kwargs: dict[str, Any]) -> None: ...
  32. __doctest_requires__ = {
  33. ("deep_noise_suppression_mean_opinion_score", "_load_session"): ["requests", "librosa", "onnxruntime"]
  34. }
  35. SAMPLING_RATE = 16000
  36. INPUT_LENGTH = 9.01
  37. DNSMOS_DIR = "~/.torchmetrics/DNSMOS"
  38. def _prepare_dnsmos(dnsmos_dir: str) -> None:
  39. """Download required DNSMOS files.
  40. Args:
  41. dnsmos_dir: a dir to save the downloaded files. Defaults to "~/.torchmetrics".
  42. """
  43. # https://raw.githubusercontent.com/microsoft/DNS-Challenge/master/DNSMOS/DNSMOS/model_v8.onnx
  44. # https://raw.githubusercontent.com/microsoft/DNS-Challenge/master/DNSMOS/DNSMOS/sig_bak_ovr.onnx
  45. # https://raw.githubusercontent.com/microsoft/DNS-Challenge/master/DNSMOS/pDNSMOS/sig_bak_ovr.onnx
  46. url = "https://raw.githubusercontent.com/microsoft/DNS-Challenge/master"
  47. dnsmos_dir = os.path.expanduser(dnsmos_dir)
  48. # save to or load from ~/torchmetrics/dnsmos/.
  49. for file in ["DNSMOS/DNSMOS/model_v8.onnx", "DNSMOS/DNSMOS/sig_bak_ovr.onnx", "DNSMOS/pDNSMOS/sig_bak_ovr.onnx"]:
  50. saveto = os.path.join(dnsmos_dir, file[7:])
  51. os.makedirs(os.path.dirname(saveto), exist_ok=True)
  52. if os.path.exists(saveto):
  53. # try loading onnx
  54. try:
  55. _ = InferenceSession(saveto)
  56. continue # skip downloading if succeeded
  57. except Exception as _:
  58. os.remove(saveto)
  59. urlf = f"{url}/{file}"
  60. rank_zero_info(f"downloading {urlf} to {saveto}")
  61. myfile = requests.get(urlf)
  62. with open(saveto, "wb") as f:
  63. f.write(myfile.content)
  64. def _load_session(
  65. path: str,
  66. device: torch.device,
  67. num_threads: Optional[int] = None,
  68. ) -> InferenceSession:
  69. """Load onnxruntime session.
  70. Args:
  71. path: the model path
  72. device: the device used
  73. num_threads: the number of threads to use. Defaults to None.
  74. Returns:
  75. onnxruntime session
  76. """
  77. path = os.path.expanduser(path)
  78. if not os.path.exists(path):
  79. _prepare_dnsmos(DNSMOS_DIR)
  80. opts = ort.SessionOptions()
  81. if num_threads is not None:
  82. opts.inter_op_num_threads = num_threads
  83. opts.intra_op_num_threads = num_threads
  84. if device.type == "cpu":
  85. infs = InferenceSession(path, providers=["CPUExecutionProvider"], sess_options=opts)
  86. elif "CUDAExecutionProvider" in ort.get_available_providers(): # win or linux with cuda
  87. providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
  88. provider_options = [{"device_id": device.index}, {}]
  89. infs = InferenceSession(path, providers=providers, provider_options=provider_options, sess_options=opts)
  90. elif "CoreMLExecutionProvider" in ort.get_available_providers(): # macos with coreml
  91. providers = ["CoreMLExecutionProvider", "CPUExecutionProvider"]
  92. provider_options = [{"device_id": device.index}, {}]
  93. infs = InferenceSession(path, providers=providers, provider_options=provider_options, sess_options=opts)
  94. else:
  95. infs = InferenceSession(path, providers=["CPUExecutionProvider"], sess_options=opts)
  96. return infs
  97. _cached_load_session = lru_cache()(_load_session)
  98. def _audio_melspec(
  99. audio: np.ndarray,
  100. n_mels: int = 120,
  101. frame_size: int = 320,
  102. hop_length: int = 160,
  103. sr: int = 16000,
  104. to_db: bool = True,
  105. ) -> np.ndarray:
  106. """Calculate the mel-spectrogram of an audio.
  107. Args:
  108. audio: [..., T]
  109. n_mels: the number of mel-frequencies
  110. frame_size: stft length
  111. hop_length: stft hop length
  112. sr: sample rate of audio
  113. to_db: convert to dB scale if `True` is given
  114. Returns:
  115. mel-spectrogram: [..., num_mel, T']
  116. """
  117. shape = audio.shape
  118. audio = audio.reshape(-1, shape[-1])
  119. mel_spec = librosa.feature.melspectrogram(
  120. y=audio, sr=sr, n_fft=frame_size + 1, hop_length=hop_length, n_mels=n_mels
  121. )
  122. mel_spec = mel_spec.transpose(0, 2, 1)
  123. mel_spec = mel_spec.reshape(shape[:-1] + mel_spec.shape[1:])
  124. if to_db:
  125. for b in range(mel_spec.shape[0]):
  126. mel_spec[b, ...] = (librosa.power_to_db(mel_spec[b], ref=np.max) + 40) / 40
  127. return mel_spec
  128. def _polyfit_val(mos: np.ndarray, personalized: bool) -> np.ndarray:
  129. """Use polyfit to convert raw mos values to DNSMOS values.
  130. Args:
  131. mos: the raw mos values, [..., 4]
  132. personalized: whether interfering speaker is penalized
  133. Returns:
  134. DNSMOS: [..., 4]
  135. """
  136. if personalized:
  137. p_ovr = np.poly1d([-0.00533021, 0.005101, 1.18058466, -0.11236046])
  138. p_sig = np.poly1d([-0.01019296, 0.02751166, 1.19576786, -0.24348726])
  139. p_bak = np.poly1d([-0.04976499, 0.44276479, -0.1644611, 0.96883132])
  140. else:
  141. p_ovr = np.poly1d([-0.06766283, 1.11546468, 0.04602535])
  142. p_sig = np.poly1d([-0.08397278, 1.22083953, 0.0052439]) # x**2*v0 + x**1*v1+ v2
  143. p_bak = np.poly1d([-0.13166888, 1.60915514, -0.39604546])
  144. mos[..., 1] = p_sig(mos[..., 1])
  145. mos[..., 2] = p_bak(mos[..., 2])
  146. mos[..., 3] = p_ovr(mos[..., 3])
  147. return mos
  148. def deep_noise_suppression_mean_opinion_score(
  149. preds: Tensor,
  150. fs: int,
  151. personalized: bool,
  152. device: Optional[str] = None,
  153. num_threads: Optional[int] = None,
  154. cache_session: bool = True,
  155. ) -> Tensor:
  156. """Calculate `Deep Noise Suppression performance evaluation based on Mean Opinion Score`_ (DNSMOS).
  157. Human subjective evaluation is the ”gold standard” to evaluate speech quality optimized for human perception.
  158. Perceptual objective metrics serve as a proxy for subjective scores. The conventional and widely used metrics
  159. require a reference clean speech signal, which is unavailable in real recordings. The no-reference approaches
  160. correlate poorly with human ratings and are not widely adopted in the research community. One of the biggest
  161. use cases of these perceptual objective metrics is to evaluate noise suppression algorithms. DNSMOS generalizes
  162. well in challenging test conditions with a high correlation to human ratings in stack ranking noise suppression
  163. methods. More details can be found in `DNSMOS paper <https://arxiv.org/abs/2010.15258>`_ and
  164. `DNSMOS P.835 paper <https://arxiv.org/abs/2110.01763>`_.
  165. .. hint::
  166. Using this metric requires you to have ``librosa``, ``onnxruntime`` and ``requests`` installed. Install
  167. as ``pip install torchmetrics['audio']`` or alternatively ``pip install librosa onnxruntime-gpu requests``
  168. (if you do not have GPU enabled machine install ``onnxruntime`` instead of ``onnxruntime-gpu``)
  169. Args:
  170. preds: [..., time]
  171. fs: sampling frequency
  172. personalized: whether interfering speaker is penalized
  173. device: the device used for calculating DNSMOS, can be cpu or cuda:n, where n is the index of gpu.
  174. If None is given, then the device of input is used.
  175. num_threads: the number of threads to use for cpu inference. Defaults to None.
  176. cache_session: whether to cache the onnx session. By default this is true, meaning that repeated calls to this
  177. method is faster than if this was set to False, the consequence is that the session will be cached in
  178. memory until the process is terminated.
  179. Returns:
  180. Float tensor with shape ``(...,4)`` of DNSMOS values per sample, i.e. [p808_mos, mos_sig, mos_bak, mos_ovr]
  181. Raises:
  182. ModuleNotFoundError:
  183. If ``librosa``, ``onnxruntime`` or ``requests`` packages are not installed
  184. Example:
  185. >>> from torch import randn
  186. >>> from torchmetrics.functional.audio.dnsmos import deep_noise_suppression_mean_opinion_score
  187. >>> preds = randn(8000)
  188. >>> deep_noise_suppression_mean_opinion_score(preds, 8000, False)
  189. tensor([2.2..., 2.0..., 1.1..., 1.2...], dtype=torch.float64)
  190. """
  191. if not _LIBROSA_AVAILABLE or not _ONNXRUNTIME_AVAILABLE or not _REQUESTS_AVAILABLE:
  192. raise ModuleNotFoundError(
  193. "DNSMOS metric requires that librosa, onnxruntime and requests are installed."
  194. " Install as `pip install librosa onnxruntime-gpu requests`."
  195. )
  196. device = torch.device(device) if device is not None else preds.device
  197. _load_session_function = _cached_load_session if cache_session else _load_session
  198. onnx_sess = _load_session_function(
  199. f"{DNSMOS_DIR}/{'p' if personalized else ''}DNSMOS/sig_bak_ovr.onnx", device, num_threads
  200. )
  201. p808_onnx_sess = _load_session_function(f"{DNSMOS_DIR}/DNSMOS/model_v8.onnx", device, num_threads)
  202. desired_fs = SAMPLING_RATE
  203. if fs != desired_fs:
  204. audio = librosa.resample(preds.cpu().numpy(), orig_sr=fs, target_sr=desired_fs)
  205. else:
  206. audio = preds.cpu().numpy()
  207. len_samples = int(INPUT_LENGTH * desired_fs)
  208. while audio.shape[-1] < len_samples:
  209. audio = np.concatenate([audio, audio], axis=-1)
  210. num_hops = int(np.floor(audio.shape[-1] / desired_fs) - INPUT_LENGTH) + 1
  211. moss = []
  212. hop_len_samples = desired_fs
  213. for idx in range(num_hops):
  214. audio_seg = audio[..., int(idx * hop_len_samples) : int((idx + INPUT_LENGTH) * hop_len_samples)]
  215. if audio_seg.shape[-1] < len_samples:
  216. continue
  217. shape = audio_seg.shape
  218. audio_seg = audio_seg.reshape((-1, shape[-1]))
  219. input_features = np.array(audio_seg).astype("float32")
  220. p808_input_features = np.array(_audio_melspec(audio=audio_seg[..., :-160])).astype("float32")
  221. if device.type != "cpu" and (
  222. "CUDAExecutionProvider" in ort.get_available_providers()
  223. or "CoreMLExecutionProvider" in ort.get_available_providers()
  224. ):
  225. try:
  226. input_features = ort.OrtValue.ortvalue_from_numpy(input_features, device.type, device.index)
  227. p808_input_features = ort.OrtValue.ortvalue_from_numpy(p808_input_features, device.type, device.index)
  228. except Exception as e:
  229. rank_zero_warn(f"Failed to use GPU for DNSMOS, reverting to CPU. Error: {e}")
  230. oi = {"input_1": input_features}
  231. p808_oi = {"input_1": p808_input_features}
  232. mos_np = np.concatenate(
  233. [p808_onnx_sess.run(None, p808_oi)[0], onnx_sess.run(None, oi)[0]], axis=-1, dtype="float64"
  234. )
  235. mos_np = _polyfit_val(mos_np, personalized)
  236. mos_np = mos_np.reshape((*shape[:-1], 4))
  237. moss.append(mos_np)
  238. return torch.from_numpy(np.mean(np.stack(moss, axis=-1), axis=-1)) # [p808_mos, mos_sig, mos_bak, mos_ovr]