
    i                     |    d dl mZ 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
 ddgiZ	 	 dded	ed
ededededefdZy)    )AnyN)Tensor)_check_same_shape)_MULTIPROCESSING_AVAILABLE_PESQ_AVAILABLE)$perceptual_evaluation_speech_qualitypesqpredstargetfsmodekeep_same_devicen_processesreturnc           	      6   t         st        d      ddl}dt        dt        fd}t        j                  |      }|dvrt        d|       |d	vrt        d
|       t        | |       | j                  dk(  r|j                  ||j                         j                         j                         | j                         j                         j                         |      }	t        j                  |	      }
n| j                  d| j                   d         j                         j                         j                         }|j                  d| j                   d         j                         j                         j                         }t"        r1|dk7  r,|j%                  |||||      }	t        j&                  |	      }	net        j(                  |j                   d         }	t+        |j                   d         D ]'  }|j                  |||ddf   ||ddf   |      |	|<   ) t        j,                  |	 ||	         j/                  t
        j0                              }
|
j                  t3        |
            }
|r|
j5                  | j6                        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 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.

    .. hint::
        Usingsing 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 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.

    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
        >>> preds = randn(8000)
        >>> target = randn(8000)
        >>> perceptual_evaluation_speech_quality(preds, target, 8000, 'nb')
        tensor(2.2885)
        >>> perceptual_evaluation_speech_quality(preds, target, 16000, 'wb')
        tensor(1.6805)

    zwPESQ metric requires that pesq is installed. Either install as `pip install torchmetrics[audio]` or `pip install pesq`.r   Nxr   c                 \    t        j                  t        |       t         j                        S )N)np
issubdtypetypenumber)r   s    w/Volumes/fast/ai/experiments/voice-extract-mac/.venv/lib/python3.12/site-packages/torchmetrics/functional/audio/pesq.py_issubtype_numberz?perceptual_evaluation_speech_quality.<locals>._issubtype_numberY   s    }}T!Wbii00    )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    )n_processor)shape)r   ModuleNotFoundErrorr	   r   boolr   	vectorize
ValueErrorr   ndimdetachcpunumpytorchtensorreshaper    r   
pesq_batcharrayemptyrange
from_numpyastypefloat32lentodevice)r
   r   r   r   r   r   pesq_backendr   _filter_error_msgpesq_val_nppesq_valpreds_np	target_npbs                 r   r   r      s<   p !Z
 	
  1S 1T 1 %67	UVXUYZ[[<VW[V\]^^eV$zzQ"''FMMO,?,?,A,G,G,I5<<>K]K]K_KeKeKgimn<<,==U[[_5<<>BBDJJLNN2u{{27>>@DDFLLN	%+*:&11"i4]h1iK((;/K(((..*;=K8>>!,-!-!2!22yAQRTUQUX\!]A .##K0A+0N$O$V$VWYWaWa$bc##CM2{{5<<((Or   )Fr   )typingr   r(   r   r)   r   torchmetrics.utilities.checksr   torchmetrics.utilities.importsr   r   __doctest_requires__intstrr"   r    r   r   <module>rD      s}        ; VAF8L  #^^^ 	^ 	^
 ^ ^ ^r   