o
    .wiy                     @   s   d dl mZ d dlmZmZmZ d dlZd dlmZmZ d dl	m
Z
 d dlmZ d dlmZmZmZmZ d dlmZmZ d	g d
iZesGdgZG dd	 d	eZdS )    )Sequence)AnyOptionalUnionN)Tensortensor))deep_noise_suppression_mean_opinion_score)Metric)_LIBROSA_AVAILABLE_MATPLOTLIB_AVAILABLE_ONNXRUNTIME_AVAILABLE_REQUESTS_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPE$DeepNoiseSuppressionMeanOpinionScore)requestslibrosaonnxruntime)DeepNoiseSuppressionMeanOpinionScore.plotc                       s   e Zd ZU dZeed< eed< dZeed< dZeed< dZ	eed< d	Z
eed
< dZeed< 			d dededee dee dededdf fddZdeddfddZdefddZd!deeee df dee defddZ  ZS )"r   uO  Calculate `Deep Noise Suppression performance evaluation based on Mean Opinion Score`_ (DNSMOS).

    Human subjective evaluation is the ”gold standard” to evaluate speech quality optimized for human perception.
    Perceptual objective metrics serve as a proxy for subjective scores. The conventional and widely used metrics
    require a reference clean speech signal, which is unavailable in real recordings. The no-reference approaches
    correlate poorly with human ratings and are not widely adopted in the research community. One of the biggest
    use cases of these perceptual objective metrics is to evaluate noise suppression algorithms. DNSMOS generalizes
    well in challenging test conditions with a high correlation to human ratings in stack ranking noise suppression
    methods. More details can be found in `DNSMOS paper <https://arxiv.org/abs/2010.15258>`_ and
    `DNSMOS P.835 paper <https://arxiv.org/abs/2110.01763>`_.


    As input to ``forward`` and ``update`` the metric accepts the following input

    - ``preds`` (:class:`~torch.Tensor`): float tensor with shape ``(...,time)``

    As output of ``forward`` and ``compute`` the metric returns the following output

    - ``dnsmos`` (:class:`~torch.Tensor`): float tensor of DNSMOS values reduced across the batch
        with shape ``(...,4)`` indicating [p808_mos, mos_sig, mos_bak, mos_ovr] in the last dim.

    .. hint::
        Using this metric requires you to have ``librosa``, ``onnxruntime`` and ``requests`` installed.
        Install as ``pip install torchmetrics['audio']`` or alternatively `pip install librosa onnxruntime-gpu requests`
        (if you do not have GPU enabled machine install `onnxruntime` instead of `onnxruntime-gpu`)

    .. caution::
        The ``forward`` and ``compute`` methods in this class return a reduced DNSMOS value
        for a batch. To obtain the DNSMOS value for each sample, you may use the functional counterpart in
        :func:`~torchmetrics.functional.audio.dnsmos.deep_noise_suppression_mean_opinion_score`.

    Args:
        fs: sampling frequency
        personalized: whether interfering speaker is penalized
        device: the device used for calculating DNSMOS, can be cpu or cuda:n, where n is the index of gpu.
            If None is given, then the device of input is used.
        num_threads: number of threads to use for onnxruntime CPU inference.
        cache_session: whether to cache the onnx session. By default this is true, meaning that repeated calls to this
            method is faster than if this was set to False, the consequence is that the session will be cached in
            memory until the process is terminated.

    Raises:
        ModuleNotFoundError:
            If ``librosa``, ``onnxruntime`` or ``requests`` packages are not installed

    Example:
        >>> from torch import randn
        >>> from torchmetrics.audio import DeepNoiseSuppressionMeanOpinionScore
        >>> preds = randn(8000)
        >>> dnsmos = DeepNoiseSuppressionMeanOpinionScore(8000, False)
        >>> dnsmos(preds)
        tensor([2.2..., 2.0..., 1.1..., 1.2...], dtype=torch.float64)

    
sum_dnsmostotalFfull_state_updateis_differentiableThigher_is_betterr   plot_lower_bound   plot_upper_boundNfspersonalizeddevicenum_threadscache_sessionskwargsreturnc                    s   t  jdi | trtrtstd|dkst|ts td|| _	t|t
s,td|| _|| _|| _|| _| jdtg dtjddd	 | jd
tddd	 d S )NzDNSMOS metric requires that librosa, onnxruntime and requests are installed. Install as `pip install librosa onnxruntime-gpu requests`.r   z)Argument `fs` must be a positive integer.z*Argument `personalized` must be a boolean.r   )r   r   r   r   )dtypesum)defaultdist_reduce_fxr    )super__init__r
   r   r   ModuleNotFoundError
isinstanceint
ValueErrorr   boolr   
cal_devicer    r!   	add_stater   torchfloat64)selfr   r   r   r    r!   r"   	__class__r(   V/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/audio/dnsmos.pyr*   d   s    	
z-DeepNoiseSuppressionMeanOpinionScore.__init__predsc                 C   sf   t || j| j| j| j| jd| jj}|  j|	ddj
dd7  _|  j|	ddjd 7  _dS )zUpdate state with predictions.)r8   r   r   r   r    cache_session   r   )dimN)r   r   r   r0   r    r!   tor   r   reshaper%   r   shape)r4   r8   metric_batchr(   r(   r7   update   s   
	 z+DeepNoiseSuppressionMeanOpinionScore.updatec                 C   s   | j | j S )zCompute metric.)r   r   )r4   r(   r(   r7   compute   s   z,DeepNoiseSuppressionMeanOpinionScore.computevalaxc                 C   s   |  ||S )aS  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling ``metric.forward`` or ``metric.compute`` or a list of these
                results. If no value is provided, will automatically call ``metric.compute`` and plot that result.
            ax: A matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If ``matplotlib`` is not installed

        .. plot::
            :scale: 75

            >>> # Example plotting a single value
            >>> import torch
            >>> from torchmetrics.audio import DeepNoiseSuppressionMeanOpinionScore
            >>> metric = DeepNoiseSuppressionMeanOpinionScore(8000, False)
            >>> metric.update(torch.rand(8000))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.audio import DeepNoiseSuppressionMeanOpinionScore
            >>> metric = DeepNoiseSuppressionMeanOpinionScore(8000, False)
            >>> values = [ ]
            >>> for _ in range(10):
            ...     values.append(metric(torch.rand(8000)))
            >>> fig_, ax_ = metric.plot(values)

        )_plot)r4   rC   rD   r(   r(   r7   plot   s   &r   )NNT)NN)__name__
__module____qualname____doc__r   __annotations__r   r/   r   r   r   floatr   r-   r   strr   r*   rA   rB   r   r   r   r   rF   __classcell__r(   r(   r5   r7   r   $   s<   
 72)collections.abcr   typingr   r   r   r2   r   r   $torchmetrics.functional.audio.dnsmosr   torchmetrics.metricr	   torchmetrics.utilities.importsr
   r   r   r   torchmetrics.utilities.plotr   r   __doctest_requires____doctest_skip__r   r(   r(   r(   r7   <module>   s   