a
    d                  	   @   st   d dl Zd dlZd dlmZ d dlmZ d dlmZmZ erFd dl	Z
ndZ
ddgiZdeeeeeeed	d
dZdS )    N)Tensor)_check_same_shape)_MULTIPROCESSING_AVAILABLE_PESQ_AVAILABLE)$perceptual_evaluation_speech_qualitypesqF   )predstargetfsmodekeep_same_devicen_processesreturnc              	   C   sp  t std|dvr"td| |dvr8td| t| | | jdkrt||  	 |   	 |}t
|}n| d| jd   	 }|d| jd   	 }	tr|dkrtj||	|||d}t|}nTtj|jd	 d
}t|jd	 D ]2}
t||	|
ddf ||
ddf |||
< qt
|}|| jdd }|rl|| jS |S )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 ect. 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.

    .. note:: using this metrics requires you to have ``pesq`` install. Either install as ``pip install
        torchmetrics[audio]`` or ``pip install pesq``. Note that ``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``.

    Args:
        preds: float tensor with shape ``(...,time)``
        target: float tensor with shape ``(...,time)``
        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 specifiying the number of processes to run in parallel for the metric calculation.
            Only applies to batches of data and if ``multiprocessing`` package is installed.

    Returns:
        Float tensor with shape ``(...,)`` of PESQ values per sample

    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"``
        RuntimeError:
            If ``preds`` and ``target`` do not have the same shape

    Example:
        >>> from torch import randn
        >>> from torchmetrics.functional.audio.pesq import perceptual_evaluation_speech_quality
        >>> g = torch.manual_seed(1)
        >>> preds = randn(8000)
        >>> target = randn(8000)
        >>> perceptual_evaluation_speech_quality(preds, target, 8000, 'nb')
        tensor(2.2076)
        >>> perceptual_evaluation_speech_quality(preds, target, 16000, 'wb')
        tensor(1.7359)

    zwPESQ 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   )Zn_processorr   )shapeN)r   ModuleNotFoundError
ValueErrorr   ndimpesq_backendr   detachcpunumpytorchZtensorZreshaper   r   Z
pesq_batchnparrayemptyrangeZ
from_numpytoZdevice)r	   r
   r   r   r   r   Zpesq_val_npZpesq_valZpreds_npZ	target_npb r"   k/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/functional/audio/pesq.pyr      s2    8

(0
r   )Fr   )r   r   r   r   Ztorchmetrics.utilities.checksr   Ztorchmetrics.utilities.importsr   r   r   r   Z__doctest_requires__intstrboolr   r"   r"   r"   r#   <module>   s&   

  