§
    ’©ºj´  ã                   óž   — d dl mZ d dlmZmZm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 d dlmZmZ dd	giZesd
gZ G d„ de¦  «        ZdS )é    )ÚSequence)ÚAnyÚOptionalÚUnion)ÚTensorÚtensor)Ú$perceptual_evaluation_speech_quality)ÚMetric)Ú_MATPLOTLIB_AVAILABLEÚ_PESQ_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEÚ!PerceptualEvaluationSpeechQualityÚpesqz&PerceptualEvaluationSpeechQuality.plotc                   óø   ‡ — 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deddf
ˆ fd„Zdededdfd„Zdefd„Zddeeee         df         dee         defd„Zˆ xZS )r   aå
  Calculate `Perceptual Evaluation of Speech Quality`_ (PESQ).

    It's a recognized industry standard for audio quality that takes into considerations characteristics such as:
    audio sharpness, call volume, background noise, clipping, audio interference etc. PESQ returns a score between
    -0.5 and 4.5 with the higher scores indicating a better quality.

    This metric is a wrapper for the `pesq package`_. Note that input will be moved to ``cpu`` to perform the metric
    calculation.

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

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

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

    - ``pesq`` (:class:`~torch.Tensor`): float tensor of PESQ value reduced across the batch

    .. hint::
        Using this metrics requires you to have ``pesq`` install. Either install as ``pip install
        torchmetrics[audio]`` or ``pip install pesq``. ``pesq`` will compile with your currently
        installed version of numpy, meaning that if you upgrade numpy at some point in the future you will
        most likely have to reinstall ``pesq``.

    .. caution::
        The ``forward`` and ``compute`` methods in this class return a single (reduced) PESQ value
        for a batch. To obtain a PESQ value for each sample, you may use the functional counterpart in
        :func:`~torchmetrics.functional.audio.pesq.perceptual_evaluation_speech_quality`.

    Args:
        fs: sampling frequency, should be 16000 or 8000 (Hz)
        mode: ``'wb'`` (wide-band) or ``'nb'`` (narrow-band)
        keep_same_device: whether to move the pesq value to the device of preds
        n_processes: integer specifying the number of processes to run in parallel for the metric calculation.
            Only applies to batches of data and if ``multiprocessing`` package is installed.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ModuleNotFoundError:
            If ``pesq`` package is not installed
        ValueError:
            If ``fs`` is not either  ``8000`` or ``16000``
        ValueError:
            If ``mode`` is not either ``"wb"`` or ``"nb"``

    Example:
        >>> from torch import randn
        >>> from torchmetrics.audio import PerceptualEvaluationSpeechQuality
        >>> preds = randn(8000)
        >>> target = randn(8000)
        >>> pesq = PerceptualEvaluationSpeechQuality(8000, 'nb')
        >>> pesq(preds, target)
        tensor(2.2885)
        >>> wb_pesq = PerceptualEvaluationSpeechQuality(16000, 'wb')
        >>> wb_pesq(preds, target)
        tensor(1.6805)

    Úsum_pesqÚtotalFÚfull_state_updateÚis_differentiableTÚhigher_is_betterg      à¿Úplot_lower_boundg      @Úplot_upper_boundé   ÚfsÚmodeÚn_processesÚkwargsÚreturnNc                 óÖ  •—  t          ¦   «         j        di |¤Ž t          st          d¦  «        ‚|dvrt	          d|› �¦  «        ‚|| _        |dvrt	          d|› �¦  «        ‚|| _        t          |t          ¦  «        s|dk    rt	          d|› �¦  «        ‚|| _	        |  
                    dt          d	¦  «        d
¬¦  «         |  
                    dt          d¦  «        d
¬¦  «         d S )Nz–PerceptualEvaluationSpeechQuality metric requires that `pesq` is installed. Either install as `pip install torchmetrics[audio]` or `pip install pesq`.)i@  i€>  z:Expected argument `fs` to either be 8000 or 16000 but got )ÚwbÚnbz;Expected argument `mode` to either be 'wb' or 'nb' but got r   zCExpected argument `n_processes` to be an int larger than 0 but got r   g        Úsum)ÚdefaultÚdist_reduce_fxr   © )ÚsuperÚ__init__r   ÚModuleNotFoundErrorÚ
ValueErrorr   r   Ú
isinstanceÚintr   Ú	add_stater   )Úselfr   r   r   r   Ú	__class__s        €úg/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/torchmetrics/audio/pesq.pyr'   z*PerceptualEvaluationSpeechQuality.__init__b   s  ø€ ð 	�‰ŒÔÐ"Ð"˜6Ð"Ð"Ð"Ýð 	Ý%ð^ñô ð ð �]Ð"Ð"ÝÐ^ÐZ\Ð^Ð^Ñ_Ô_Ð_ØˆŒØ�|Ð#Ð#ÝÐaÐ[_ÐaÐaÑbÔbÐbØˆŒ	Ý˜+¥sÑ+Ô+ð 	r°¸qÒ0@Ð0@ÝÐpÐcnÐpÐpÑqÔqÐqØ&ˆÔà�Š�z­6°#©;¬;ÀuˆÑMÔMÐMØ�Š�w­¨q©	¬	À%ˆÑHÔHÐHÐHÐHó    ÚpredsÚtargetc                 ó  — t          ||| j        | j        d| j        ¦  «                             | j        j        ¦  «        }| xj        |                     ¦   «         z  c_        | xj        | 	                    ¦   «         z  c_        dS )z*Update state with predictions and targets.FN)
r	   r   r   r   Útor   Údevicer"   r   Únumel)r-   r1   r2   Ú
pesq_batchs       r/   Úupdatez(PerceptualEvaluationSpeechQuality.update|   sv   € å9Ø�6˜4œ7 D¤I¨u°dÔ6Fñ
ô 
ç
Š"ˆTŒ]Ô!Ñ
"Ô
"ð 	ð 	ˆŒ˜ŸšÑ)Ô)Ñ)ˆŒØˆ
Œ
�j×&Ò&Ñ(Ô(Ñ(ˆ
Œ
ˆ
ˆ
r0   c                 ó    — | j         | j        z  S )zCompute metric.)r   r   )r-   s    r/   Úcomputez)PerceptualEvaluationSpeechQuality.compute…   s   € àŒ}˜tœzÑ)Ð)r0   ÚvalÚaxc                 ó.   — |                       ||¦  «        S )ab  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: An 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 PerceptualEvaluationSpeechQuality
            >>> metric = PerceptualEvaluationSpeechQuality(8000, 'nb')
            >>> metric.update(torch.rand(8000), torch.rand(8000))
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

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

        )Ú_plot)r-   r;   r<   s      r/   Úplotz&PerceptualEvaluationSpeechQuality.plot‰   s   € ðL �zŠz˜#˜rÑ"Ô"Ð"r0   )r   )NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__annotations__r   Úboolr   r   r   Úfloatr   r+   Ústrr   r'   r8   r:   r   r   r   r   r   r?   Ú__classcell__)r.   s   @r/   r   r      s†  ø€ € € € € € ð9ð 9ðv ÐÐÑØ€M€M�MØ#Ð�tÐ#Ð#Ñ#Ø#Ð�tÐ#Ð#Ñ#Ø!Ð�dÐ!Ð!Ñ!Ø"Ð�eÐ"Ð"Ñ"Ø!Ð�eÐ!Ð!Ñ!ð ð	Ið IàðIð ðIð ð	Ið
 ðIð 
ðIð Ið Ið Ið Ið Ið4)˜Fð )¨Fð )°tð )ð )ð )ð )ð*˜ð *ð *ð *ð *ð&#ð &#˜˜f h¨vÔ&6¸Ð<Ô=ð &#È(ÐS[ÔJ\ð &#Ðhvð &#ð &#ð &#ð &#ð &#ð &#ð &#ð &#r0   N)Úcollections.abcr   Útypingr   r   r   Útorchr   r   Ú"torchmetrics.functional.audio.pesqr	   Útorchmetrics.metricr
   Útorchmetrics.utilities.importsr   r   Útorchmetrics.utilities.plotr   r   Ú__doctest_requires__Ú__doctest_skip__r   r%   r0   r/   ú<module>rR      s   ðð %Ð $Ð $Ð $Ð $Ð $Ø 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'Ð 'à  Ð  Ð  Ð  Ð  Ð  Ð  Ð  à SÐ SÐ SÐ SÐ SÐ SØ &Ð &Ð &Ð &Ð &Ð &Ø QÐ QÐ QÐ QÐ QÐ QÐ QÐ QØ @Ð @Ð @Ð @Ð @Ð @Ð @Ð @à;¸f¸XÐFÐ àð BØ@ÐAÐðQ#ð Q#ð Q#ð Q#ð Q#¨ñ Q#ô Q#ð Q#ð Q#ð Q#r0   