pesq.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. from collections.abc import Sequence
  15. from typing import Any, Optional, Union
  16. from torch import Tensor, tensor
  17. from torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality
  18. from torchmetrics.metric import Metric
  19. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _PESQ_AVAILABLE
  20. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  21. __doctest_requires__ = {"PerceptualEvaluationSpeechQuality": ["pesq"]}
  22. if not _MATPLOTLIB_AVAILABLE:
  23. __doctest_skip__ = ["PerceptualEvaluationSpeechQuality.plot"]
  24. class PerceptualEvaluationSpeechQuality(Metric):
  25. """Calculate `Perceptual Evaluation of Speech Quality`_ (PESQ).
  26. It's a recognized industry standard for audio quality that takes into considerations characteristics such as:
  27. audio sharpness, call volume, background noise, clipping, audio interference etc. PESQ returns a score between
  28. -0.5 and 4.5 with the higher scores indicating a better quality.
  29. This metric is a wrapper for the `pesq package`_. Note that input will be moved to ``cpu`` to perform the metric
  30. calculation.
  31. As input to ``forward`` and ``update`` the metric accepts the following input
  32. - ``preds`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``
  33. - ``target`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``
  34. As output of `forward` and `compute` the metric returns the following output
  35. - ``pesq`` (:class:`~torch.Tensor`): float tensor of PESQ value reduced across the batch
  36. .. hint::
  37. Using this metrics requires you to have ``pesq`` install. Either install as ``pip install
  38. torchmetrics[audio]`` or ``pip install pesq``. ``pesq`` will compile with your currently
  39. installed version of numpy, meaning that if you upgrade numpy at some point in the future you will
  40. most likely have to reinstall ``pesq``.
  41. .. caution::
  42. The ``forward`` and ``compute`` methods in this class return a single (reduced) PESQ value
  43. for a batch. To obtain a PESQ value for each sample, you may use the functional counterpart in
  44. :func:`~torchmetrics.functional.audio.pesq.perceptual_evaluation_speech_quality`.
  45. Args:
  46. fs: sampling frequency, should be 16000 or 8000 (Hz)
  47. mode: ``'wb'`` (wide-band) or ``'nb'`` (narrow-band)
  48. keep_same_device: whether to move the pesq value to the device of preds
  49. n_processes: integer specifying the number of processes to run in parallel for the metric calculation.
  50. Only applies to batches of data and if ``multiprocessing`` package is installed.
  51. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  52. Raises:
  53. ModuleNotFoundError:
  54. If ``pesq`` package is not installed
  55. ValueError:
  56. If ``fs`` is not either ``8000`` or ``16000``
  57. ValueError:
  58. If ``mode`` is not either ``"wb"`` or ``"nb"``
  59. Example:
  60. >>> from torch import randn
  61. >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
  62. >>> preds = randn(8000)
  63. >>> target = randn(8000)
  64. >>> pesq = PerceptualEvaluationSpeechQuality(8000, 'nb')
  65. >>> pesq(preds, target)
  66. tensor(2.2885)
  67. >>> wb_pesq = PerceptualEvaluationSpeechQuality(16000, 'wb')
  68. >>> wb_pesq(preds, target)
  69. tensor(1.6805)
  70. """
  71. sum_pesq: Tensor
  72. total: Tensor
  73. full_state_update: bool = False
  74. is_differentiable: bool = False
  75. higher_is_better: bool = True
  76. plot_lower_bound: float = -0.5
  77. plot_upper_bound: float = 4.5
  78. def __init__(
  79. self,
  80. fs: int,
  81. mode: str,
  82. n_processes: int = 1,
  83. **kwargs: Any,
  84. ) -> None:
  85. super().__init__(**kwargs)
  86. if not _PESQ_AVAILABLE:
  87. raise ModuleNotFoundError(
  88. "PerceptualEvaluationSpeechQuality metric requires that `pesq` is installed."
  89. " Either install as `pip install torchmetrics[audio]` or `pip install pesq`."
  90. )
  91. if fs not in (8000, 16000):
  92. raise ValueError(f"Expected argument `fs` to either be 8000 or 16000 but got {fs}")
  93. self.fs = fs
  94. if mode not in ("wb", "nb"):
  95. raise ValueError(f"Expected argument `mode` to either be 'wb' or 'nb' but got {mode}")
  96. self.mode = mode
  97. if not isinstance(n_processes, int) and n_processes <= 0:
  98. raise ValueError(f"Expected argument `n_processes` to be an int larger than 0 but got {n_processes}")
  99. self.n_processes = n_processes
  100. self.add_state("sum_pesq", default=tensor(0.0), dist_reduce_fx="sum")
  101. self.add_state("total", default=tensor(0), dist_reduce_fx="sum")
  102. def update(self, preds: Tensor, target: Tensor) -> None:
  103. """Update state with predictions and targets."""
  104. pesq_batch = perceptual_evaluation_speech_quality(
  105. preds, target, self.fs, self.mode, False, self.n_processes
  106. ).to(self.sum_pesq.device)
  107. self.sum_pesq += pesq_batch.sum()
  108. self.total += pesq_batch.numel()
  109. def compute(self) -> Tensor:
  110. """Compute metric."""
  111. return self.sum_pesq / self.total
  112. def plot(self, val: Union[Tensor, Sequence[Tensor], None] = None, ax: Optional[_AX_TYPE] = None) -> _PLOT_OUT_TYPE:
  113. """Plot a single or multiple values from the metric.
  114. Args:
  115. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  116. If no value is provided, will automatically call `metric.compute` and plot that result.
  117. ax: An matplotlib axis object. If provided will add plot to that axis
  118. Returns:
  119. Figure and Axes object
  120. Raises:
  121. ModuleNotFoundError:
  122. If `matplotlib` is not installed
  123. .. plot::
  124. :scale: 75
  125. >>> # Example plotting a single value
  126. >>> import torch
  127. >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
  128. >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
  129. >>> metric.update(torch.rand(8000), torch.rand(8000))
  130. >>> fig_, ax_ = metric.plot()
  131. .. plot::
  132. :scale: 75
  133. >>> # Example plotting multiple values
  134. >>> import torch
  135. >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
  136. >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
  137. >>> values = [ ]
  138. >>> for _ in range(10):
  139. ... values.append(metric(torch.rand(8000), torch.rand(8000)))
  140. >>> fig_, ax_ = metric.plot(values)
  141. """
  142. return self._plot(val, ax)