o
    zi                     @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dlm
Z
 d dlZd dlZd dlZd dlZddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlm Z  e	dg dZ!	 de!j"_#G dd deeeeeeee 
Z$dS )    N)
namedtuple)Path   )util)DisplayMixin)DSPMixin)EffectMixin)ImpulseResponseMixin)FFMPEGMixin)LoudnessMixin)	PlayMixin)WhisperMixin
STFTParamswindow_length
hop_lengthwindow_typematch_stridepadding_typeNNNNNc                   @   s$  e Zd ZdZ					ddejejee	e
jf dedededed	efd
dZedd Ze			ddejee	f dededeje
jjef fddZe			ddejee	f dededeje
jjef fddZe		ddedededefddZe		ddededededef
dd Ze	!	!	!	dd"ed#ed$ed%ed&ef
d'd(Z	)ddejee	f deded	efd*d+Z	)dd,ejeje
jf ded	efd-d.Zdejee	f fd/d0Zd1d2 Zd3d4 Z d5d6 Z!d7d8 Z"d9d: Z#d;d< Z$defd=d>Z%d	efd?d@Z&dAdB ZdCdD Z'dEdF Z(dGdH Z)dIedJefdKdLZ*ddMedNefdOdPZ+dIedJefdQdRZ,dSefdTdUZ-edVdW Z.edXdY Z/e/j0dZejeje
jf fd[dYZ/e/Z1ed\d] Z2e2j0dZejeje
jf fd^d]Z2ed_d` Z3edadb Z4e4Z5edcdd Z6ededf Z7e7Z8edgdh Z9e:e;<ddiedjed	efdkdlZ=edmdn Z>e>j0doefdpdnZ>djedqedrefdsdtZ?					ddjedqediedreduef
dvdwZ@					ddjedqediedredMef
dxdyZAe:e;<d	dd{ed|ed}ed~edef
ddZB	dd}ededefddZCe:e;<ddded}eded	efddZD	dded}edefddZEedd ZFeFj0dd ZF	ddededefddZGedd ZHeHj0dd ZHdd ZIdd ZJdd ZKdd ZLdd ZMdd ZNdd ZOdd ZPdd ZQdd ZRdd ZSdd ZTdd ZUdd ZVdd ZWdd ZXdS )AudioSignala  This is the core object of this library. Audio is always
    loaded into an AudioSignal, which then enables all the features
    of this library, including audio augmentations, I/O, playback,
    and more.

    The structure of this object is that the base functionality
    is defined in ``core/audio_signal.py``, while extensions to
    that functionality are defined in the other ``core/*.py``
    files. For example, all the display-based functionality
    (e.g. plot spectrograms, waveforms, write to tensorboard)
    are in ``core/display.py``.

    Parameters
    ----------
    audio_path_or_array : typing.Union[torch.Tensor, str, Path, np.ndarray]
        Object to create AudioSignal from. Can be a tensor, numpy array,
        or a path to a file. The file is always reshaped to
    sample_rate : int, optional
        Sample rate of the audio. If different from underlying file, resampling is
        performed. If passing in an array or tensor, this must be defined,
        by default None
    stft_params : STFTParams, optional
        Parameters of STFT to use. , by default None
    offset : float, optional
        Offset in seconds to read from file, by default 0
    duration : float, optional
        Duration in seconds to read from file, by default None
    device : str, optional
        Device to load audio onto, by default None

    Examples
    --------
    Loading an AudioSignal from an array, at a sample rate of
    44100.

    >>> signal = AudioSignal(torch.randn(5*44100), 44100)

    Note, the signal is reshaped to have a batch size, and one
    audio channel:

    >>> print(signal.shape)
    (1, 1, 44100)

    You can treat AudioSignals like tensors, and many of the same
    functions you might use on tensors are defined for AudioSignals
    as well:

    >>> signal.to("cuda")
    >>> signal.cuda()
    >>> signal.clone()
    >>> signal.detach()

    Indexing AudioSignals returns an AudioSignal:

    >>> signal[..., 3*44100:4*44100]

    The above signal is 1 second long, and is also an AudioSignal.
    Nr   audio_path_or_arraysample_ratestft_paramsoffsetdurationdevicec           	      C   s   d }d }t |tr|}nt |tjr|}nt |tjr|}nt|r&|}ntdd | _	d | _
d | _d | _|d urD| j||||d n|d urX|d usPJ d| j|||d d | _|| _||d| _d S )NzPaudio_path_or_array must be either a Path, string, numpy array, or torch Tensor!)r   r   r   zMust set sample rate!)r   r   r   )
isinstancestrpathlibr   npndarraytorch	is_tensor
ValueErrorpath_to_file
audio_datasources	stft_dataload_from_fileload_from_arraywindowr   metadata)	selfr   r   r   r   r   r   
audio_pathaudio_array r1   P/home/ubuntu/.local/lib/python3.10/site-packages/audiotools/core/audio_signal.py__init__z   s:   	

zAudioSignal.__init__c                 C      | j S )zq
        Path to input file, if it exists.
        Alias to ``path_to_file`` for backwards compatibility
        r&   r.   r1   r1   r2   path_to_input_file   s   zAudioSignal.path_to_input_filer/   statec                 K   sr   t |}|j}t |}|du rdn|}t|| d}	|||	}| |f||d|}
||
jd< ||
jd< |
S )a  Randomly draw an excerpt of ``duration`` seconds from an
        audio file specified at ``audio_path``, between ``offset`` seconds
        and end of file. ``state`` can be used to seed the random draw.

        Parameters
        ----------
        audio_path : typing.Union[str, Path]
            Path to audio file to grab excerpt from.
        offset : float, optional
            Lower bound for the start time, in seconds drawn from
            the file, by default None.
        duration : float, optional
            Duration of excerpt, in seconds, by default None
        state : typing.Union[np.random.RandomState, int], optional
            RandomState or seed of random state, by default None

        Returns
        -------
        AudioSignal
            AudioSignal containing excerpt.

        Examples
        --------
        >>> signal = AudioSignal.excerpt("path/to/audio", duration=5)
        Nr   r   r   r   )r   infor   random_statemaxuniformr-   )clsr/   r   r   r8   kwargsr9   total_durationlower_boundupper_boundsignalr1   r1   r2   excerpt   s   
"


zAudioSignal.excerpt   loudness_cutoff	num_triesc           	      K   s   t |}|du r| j|fd|i|}|S tj }d}||krB| j|fd|i|}| }|d7 }|dur>||kr>	 |S ||ks |S )a6  Similar to AudioSignal.excerpt, except it extracts excerpts only
        if they are above a specified loudness threshold, which is computed via
        a fast LUFS routine.

        Parameters
        ----------
        audio_path : typing.Union[str, Path]
            Path to audio file to grab excerpt from.
        loudness_cutoff : float, optional
            Loudness threshold in dB. Typical values are ``-40, -60``,
            etc, by default None
        num_tries : int, optional
            Number of tries to grab an excerpt above the threshold
            before giving up, by default 8.
        state : typing.Union[np.random.RandomState, int], optional
            RandomState or seed of random state, by default None
        kwargs : dict
            Keyword arguments to AudioSignal.excerpt

        Returns
        -------
        AudioSignal
            AudioSignal containing excerpt.


        .. warning::
            if ``num_tries`` is set to None, ``salient_excerpt`` may try forever, which can
            result in an infinite loop if ``audio_path`` does not have
            any loud enough excerpts.

        Examples
        --------
        >>> signal = AudioSignal.salient_excerpt(
                "path/to/audio",
                loudness_cutoff=-40,
                duration=5
            )
        Nr8   r   r   )r   r:   rC   r!   infloudness)	r=   r/   rE   rF   r8   r>   rC   rH   num_tryr1   r1   r2   salient_excerpt   s   
/
zAudioSignal.salient_excerptr   num_channels
batch_sizec                 K   s(   t || }| t||||fi |S )ax  Helper function create an AudioSignal of all zeros.

        Parameters
        ----------
        duration : float
            Duration of AudioSignal
        sample_rate : int
            Sample rate of AudioSignal
        num_channels : int, optional
            Number of channels, by default 1
        batch_size : int, optional
            Batch size, by default 1

        Returns
        -------
        AudioSignal
            AudioSignal containing all zeros.

        Examples
        --------
        Generate 5 seconds of all zeros at a sample rate of 44100.

        >>> signal = AudioSignal.zeros(5.0, 44100)
        )intr#   zeros)r=   r   r   rK   rL   r>   	n_samplesr1   r1   r2   rN      s   !zAudioSignal.zerossine	frequencyshapec                 K   s  t || }td||}|dkr$ddlm}	 |	dtj | | d}
nM|dkr:ddlm} |dtj | | }
n7|dkrKtdtj | | }
n&|d	krjddlm}	 |	tj| | d}
t	|
 d d
 }
nt
d| tj|
tjd}
|
ddd
|d
}
| |
|fi |S )aO  
        Generate a waveform of a given frequency and shape.

        Parameters
        ----------
        frequency : float
            Frequency of the waveform
        duration : float
            Duration of the waveform
        sample_rate : int
            Sample rate of the waveform
        num_channels : int, optional
            Number of channels, by default 1
        shape : str, optional
            Shape of the waveform, by default "saw"
            One of "sawtooth", "square", "sine", "triangle"
        kwargs : dict
            Keyword arguments to AudioSignal
        r   sawtooth)rS      g      ?square)rU   rP   triangler   zInvalid shape )dtype)rM   r#   linspacescipy.signalrS   r!   pirU   sinabsr%   tensorfloat32	unsqueezerepeat)r=   rQ   r   r   rK   rR   r>   rO   trS   	wave_datarU   r1   r1   r2   waveF  s$   zAudioSignal.waveFaudio_signalspad_signalstruncate_signalsresampledimc                 C   s  dd |D }dd |D }t t|dkr-|r%|D ]	}||d  qntd| dt t|dkre|rLt|}	|D ]}|	|j }
|d|
 q=n|r]t|}|D ]}|| qTntd| d	t	j
d
d |D |d}dd |D }| ||d jd}||_|S )a  Creates a batched AudioSignal from a list of AudioSignals.

        Parameters
        ----------
        audio_signals : list[AudioSignal]
            List of AudioSignal objects
        pad_signals : bool, optional
            Whether to pad signals to length of the maximum length
            AudioSignal in the list, by default False
        truncate_signals : bool, optional
            Whether to truncate signals to length of shortest length
            AudioSignal in the list, by default False
        resample : bool, optional
            Whether to resample AudioSignal to the sample rate of
            the first AudioSignal in the list, by default False
        dim : int, optional
            Dimension along which to batch the signals.

        Returns
        -------
        AudioSignal
            Batched AudioSignal.

        Raises
        ------
        RuntimeError
            If not all AudioSignals are the same sample rate, and
            ``resample=False``, an error is raised.
        RuntimeError
            If not all AudioSignals are the same the length, and
            both ``pad_signals=False`` and ``truncate_signals=False``,
            an error is raised.

        Examples
        --------
        Batching a bunch of random signals:

        >>> signal_list = [AudioSignal(torch.randn(44100), 44100) for _ in range(10)]
        >>> signal = AudioSignal.batch(signal_list)
        >>> print(signal.shape)
        (10, 1, 44100)

        c                 S      g | ]}|j qS r1   )signal_length.0xr1   r1   r2   
<listcomp>      z%AudioSignal.batch.<locals>.<listcomp>c                 S   ri   r1   r   rk   r1   r1   r2   rn     ro   r   r   z.Not all signals had the same sample rate! Got zH. All signals must have the same sample rate, or resample must be True. z)Not all signals had the same length! Got zU. All signals must be the same length, or pad_signals/truncate_signals must be True. c                 S   ri   r1   r'   rk   r1   r1   r2   rn     ro   )rh   c                 S   ri   r1   r5   rk   r1   r1   r2   rn     ro   rp   )lensetrg   RuntimeErrorr;   rj   zero_padmintruncate_samplesr#   catr   r&   )r=   rd   re   rf   rg   rh   signal_lengthssample_ratesrm   
max_lengthpad_len
min_lengthr'   audio_pathsbatched_signalr1   r1   r2   batch|  sB   4


zAudioSignal.batchcpuc                 C   s   ddl }|j|||ddd\}}t|}|jd dkr*td| d| d| d	|jd
k r4|d}|jdk r>|d}|| _| j	| _
|| _|| _| |S )a  Loads data from file. Used internally when AudioSignal
        is instantiated with a path to a file.

        Parameters
        ----------
        audio_path : typing.Union[str, Path]
            Path to file
        offset : float
            Offset in seconds
        duration : float
            Duration in seconds
        device : str, optional
            Device to put AudioSignal on, by default "cpu"

        Returns
        -------
        AudioSignal
            AudioSignal loaded from file
        r   NF)r   r   srmonozAudio file z with offset z and duration z
 is empty!rT      )librosaloadr   ensure_tensorrR   rt   ndimr_   r'   rj   original_signal_lengthr   r&   to)r.   r/   r   r   r   r   datar   r1   r1   r2   r*     s,   






zAudioSignal.load_from_filer0   c                 C   sd   t |}|jtjkr| }|jdk r|d}|jdk r#|d}|| _| j	| _
|| _| |S )a!  Loads data from array, reshaping it to be exactly 3
        dimensions. Used internally when AudioSignal is called
        with a tensor or an array.

        Parameters
        ----------
        audio_array : typing.Union[torch.Tensor, np.ndarray]
            Array/tensor of audio of samples.
        sample_rate : int
            Sample rate of audio
        device : str, optional
            Device to move audio onto, by default "cpu"

        Returns
        -------
        AudioSignal
            AudioSignal loaded from array
        rT   r   r   )r   r   rW   r#   doublefloatr   r_   r'   rj   r   r   r   )r.   r0   r   r   r'   r1   r1   r2   r+     s   





zAudioSignal.load_from_arrayc                 C   sJ   | j d   dkrtd tt|| j d  j	| j
 || _| S )a  Writes audio to a file. Only writes the audio
        that is in the very first item of the batch. To write other items
        in the batch, index the signal along the batch dimension
        before writing. After writing, the signal's ``path_to_file``
        attribute is updated to the new path.

        Parameters
        ----------
        audio_path : typing.Union[str, Path]
            Path to write audio to.

        Returns
        -------
        AudioSignal
            Returns original AudioSignal, so you can use this in a fluent
            interface.

        Examples
        --------
        Creating and writing a signal to disk:

        >>> signal = AudioSignal(torch.randn(10, 1, 44100), 44100)
        >>> signal.write("/tmp/out.wav")

        Writing a different element of the batch:

        >>> signal[5].write("/tmp/out.wav")

        Using this in a fluent interface:

        >>> signal.write("/tmp/original.wav").low_pass(4000).write("/tmp/lowpass.wav")

        r   r   z'Audio amplitude > 1 clipped when saving)r'   r\   r;   warningswarn	soundfilewriter   numpyTr   r&   )r.   r/   r1   r1   r2   r   6  s
   "
 zAudioSignal.writec                 C   s
   t | S )zCopies the signal and all of its attributes.

        Returns
        -------
        AudioSignal
            Deep copy of the audio signal.
        )copydeepcopyr6   r1   r1   r2   r   _     
zAudioSignal.deepcopyc                 C   s
   t  | S )zShallow copy of signal.

        Returns
        -------
        AudioSignal
            Shallow copy of the audio signal.
        )r   r6   r1   r1   r2   r   i  r   zAudioSignal.copyc                 C   sh   t | | j | j| jd}| jdur| j |_| jdur$| j |_t| j	|_	t| j
|_
|S )a  Clones all tensors contained in the AudioSignal,
        and returns a copy of the signal with everything
        cloned. Useful when using AudioSignal within autograd
        computation graphs.

        Relevant attributes are the stft data, the audio data,
        and the loudness of the file.

        Returns
        -------
        AudioSignal
            Clone of AudioSignal.
        r   N)typer'   cloner   r   r)   	_loudnessr   r   r&   r-   )r.   r   r1   r1   r2   r   s  s   

zAudioSignal.clonec                 C   s<   | j dur| j  | _ | jdur| j | _| j | _| S )a  Detaches tensors contained in AudioSignal.

        Relevant attributes are the stft data, the audio data,
        and the loudness of the file.

        Returns
        -------
        AudioSignal
            Same signal, but with all tensors detached.
        N)r   detachr)   r'   r6   r1   r1   r2   r     s   

zAudioSignal.detachc              	      s   t jddM |  j t }td}t|t jddd t	 fdddD ]}|
d	|  q,W d	   n1 sBw   Y  | }W d	   |S 1 sVw   Y  |S )
a  Writes the audio data to a temporary file, and then
        hashes it using hashlib. Useful for creating a file
        name based on the audio content.

        Returns
        -------
        str
            Hash of audio data.

        Examples
        --------
        Creating a signal, and writing it to a unique file name:

        >>> signal = AudioSignal(torch.randn(44100), 44100)
        >>> hash = signal.hash()
        >>> signal.write(f"{hash}.wav")

        z.wav)suffixi   rbr   )	bufferingc                      s
     S N)readintor1   fmvr1   r2   <lambda>  s   
 z"AudioSignal.hash.<locals>.<lambda>N)tempfileNamedTemporaryFiler   namehashlibsha256	bytearray
memoryviewopeniterupdate	hexdigest)r.   hbn	file_hashr1   r   r2   hash  s   

		zAudioSignal.hashc                 C   s   | j jddd| _ | S )zConverts audio data to mono audio, by taking the mean
        along the channels dimension.

        Returns
        -------
        AudioSignal
            AudioSignal with mean of channels.
        r   T)keepdim)r'   meanr6   r1   r1   r2   to_mono  s   	zAudioSignal.to_monoc                 C   s,   || j kr| S t| j| j || _|| _ | S )a:  Resamples the audio, using sinc interpolation. This works on both
        cpu and gpu, and is much faster on gpu.

        Parameters
        ----------
        sample_rate : int
            Sample rate to resample to.

        Returns
        -------
        AudioSignal
            Resampled AudioSignal
        )r   juliusresample_fracr'   )r.   r   r1   r1   r2   rg     s   

zAudioSignal.resamplec                 C   sL   | j dur| j || _ | jdur| j|| _| jdur$| j|| _| S )a{  Moves all tensors contained in signal to the specified device.

        Parameters
        ----------
        device : str
            Device to move AudioSignal onto. Typical values are
            "cuda", "cpu", or "cuda:n" to specify the nth gpu.

        Returns
        -------
        AudioSignal
            AudioSignal with all tensors moved to specified device.
        N)r   r   r)   r'   r.   r   r1   r1   r2   r     s   


zAudioSignal.toc                 C   s   | j  | _ | S )zhCalls ``.float()`` on ``self.audio_data``.

        Returns
        -------
        AudioSignal
        )r'   r   r6   r1   r1   r2   r     s   zAudioSignal.floatc                 C   
   |  dS )zWMoves AudioSignal to cpu.

        Returns
        -------
        AudioSignal
        r   r   r6   r1   r1   r2   r        
zAudioSignal.cpuc                 C   r   )zXMoves AudioSignal to cuda.

        Returns
        -------
        AudioSignal
        cudar   r6   r1   r1   r2   r     r   zAudioSignal.cudac                 C   s   | j    S )zDetaches ``self.audio_data``, moves to cpu, and converts to numpy.

        Returns
        -------
        np.ndarray
            Audio data as a numpy array.
        )r'   r   r   r   r6   r1   r1   r2   r     s   zAudioSignal.numpybeforeafterc                 C   s   t jj| j||f| _| S )aL  Zero pads the audio_data tensor before and after.

        Parameters
        ----------
        before : int
            How many zeros to prepend to audio.
        after : int
            How many zeros to append to audio.

        Returns
        -------
        AudioSignal
            AudioSignal with padding applied.
        )r#   nn
functionalpadr'   r.   r   r   r1   r1   r2   ru     s   zAudioSignal.zero_padlengthmodec                 C   sH   |dkr|  t|| j dd | S |dkr"|  dt|| j d | S )a  Pad with zeros to a specified length, either before or after
        the audio data.

        Parameters
        ----------
        length : int
            Length to pad to
        mode : str, optional
            Whether to prepend or append zeros to signal, by default "after"

        Returns
        -------
        AudioSignal
            AudioSignal with padding applied.
        r   r   r   )ru   r;   rj   )r.   r   r   r1   r1   r2   zero_pad_to1  s   zAudioSignal.zero_pad_toc                 C   s:   |dkr| j d|df | _ | S | j d|| f | _ | S )aN  Trims the audio_data tensor before and after.

        Parameters
        ----------
        before : int
            How many samples to trim from beginning.
        after : int
            How many samples to trim from end.

        Returns
        -------
        AudioSignal
            AudioSignal with trimming applied.
        r   .Nrq   r   r1   r1   r2   trimG  s
   zAudioSignal.trimlength_in_samplesc                 C   s   | j dd|f | _ | S )a  Truncate signal to specified length.

        Parameters
        ----------
        length_in_samples : int
            Truncate to this many samples.

        Returns
        -------
        AudioSignal
            AudioSignal with truncation applied.
        .Nrq   )r.   r   r1   r1   r2   rw   \  s   zAudioSignal.truncate_samplesc                 C   s,   | j dur| j j}|S | jdur| jj}|S )zGet device that AudioSignal is on.

        Returns
        -------
        torch.device
            Device that AudioSignal is on.
        N)r'   r   r)   r   r1   r1   r2   r   l  s   
	
zAudioSignal.devicec                 C   r4   )a  Returns the audio data tensor in the object.

        Audio data is always of the shape
        (batch_size, num_channels, num_samples). If value has less
        than 3 dims (e.g. is (num_channels, num_samples)), then it will
        be reshaped to (1, num_channels, num_samples) - a batch size of 1.

        Parameters
        ----------
        data : typing.Union[torch.Tensor, np.ndarray]
            Audio data to set.

        Returns
        -------
        torch.Tensor
            Audio samples.
        )_audio_datar6   r1   r1   r2   r'   |  s   zAudioSignal.audio_datar   c                 C   s<   |d urt |sJ d|jdksJ d|| _d | _d S )Nz!audio_data should be torch.Tensorr   z$audio_data should be 3-dim (B, C, T))r#   r$   r   r   r   r.   r   r1   r1   r2   r'     s   c                 C   r4   )zReturns the STFT data inside the signal. Shape is
        (batch, channels, frequencies, time).

        Returns
        -------
        torch.Tensor
            Complex spectrogram data.
        )
_stft_datar6   r1   r1   r2   r)     s   
zAudioSignal.stft_datac                 C   sL   |d ur!t |rt |sJ | jd ur!| jj|jkr!td || _d S )Nzstft_data changed shape)r#   r$   
is_complexr)   rR   r   r   r   r   r1   r1   r2   r)     s   
c                 C      | j jd S )zsBatch size of audio signal.

        Returns
        -------
        int
            Batch size of signal.
        r   r'   rR   r6   r1   r1   r2   rL        	zAudioSignal.batch_sizec                 C   r   )zvLength of audio signal.

        Returns
        -------
        int
            Length of signal in samples.
        r   r   r6   r1   r1   r2   rj     r   zAudioSignal.signal_lengthc                 C   s   | j jS )zmShape of audio data.

        Returns
        -------
        tuple
            Shape of audio data.
        r   r6   r1   r1   r2   rR     s   	zAudioSignal.shapec                 C   s   | j | j S )zLength of audio signal in seconds.

        Returns
        -------
        float
            Length of signal in seconds.
        )rj   r   r6   r1   r1   r2   signal_duration  r   zAudioSignal.signal_durationc                 C   r   )zuNumber of audio channels.

        Returns
        -------
        int
            Number of audio channels.
        r   r   r6   r1   r1   r2   rK     r   zAudioSignal.num_channelsr   r   c                 C   sd   ddl m} | dkrt|| }n| dkr t|d|}n|| |}t||	 }|S )a  Wrapper around scipy.signal.get_window so one can also get the
        popular sqrt-hann window. This function caches for efficiency
        using functools.lru\_cache.

        Parameters
        ----------
        window_type : str
            Type of window to get
        window_length : int
            Length of the window
        device : str
            Device to put window onto.

        Returns
        -------
        torch.Tensor
            Window returned by scipy.signal.get_window, as a tensor.
        r   )rB   average	sqrt_hannhann)
scipyrB   r!   onessqrt
get_windowr#   
from_numpyr   r   )r   r   r   rB   r,   r1   r1   r2   r     s   zAudioSignal.get_windowc                 C   r4   )a  Returns STFTParams object, which can be re-used to other
        AudioSignals.

        This property can be set as well. If values are not defined in STFTParams,
        they are inferred automatically from the signal properties. The default is to use
        32ms windows, with 8ms hop length, and the square root of the hann window.

        Returns
        -------
        STFTParams
            STFT parameters for the AudioSignal.

        Examples
        --------
        >>> stft_params = STFTParams(128, 32)
        >>> signal1 = AudioSignal(torch.randn(44100), 44100, stft_params=stft_params)
        >>> signal2 = AudioSignal(torch.randn(44100), 44100, stft_params=signal1.stft_params)
        >>> signal1.stft_params = STFTParams() # Defaults
        )_stft_paramsr6   r1   r1   r2   r     s   zAudioSignal.stft_paramsvaluec           	      C   s   t dttd| j  }|d }d}d}d}t|||||d }|r*| n|}|D ]}|| d u r<|| ||< q.tdi || _d | _d S )	NrT   gMb?   r   Freflectr   r1   )	rM   r!   ceillog2r   r   _asdictr   r)   )	r.   r   default_win_lendefault_hop_lendefault_win_typedefault_match_stridedefault_padding_typedefault_stft_paramskeyr1   r1   r2   r   (  s*   
r   r   c                 C   sX   | j }|r$||d ksJ dt|| | | }|| d }||fS d}d}||fS )a  Compute how the STFT should be padded, based on match\_stride.

        Parameters
        ----------
        window_length : int
            Window length of STFT.
        hop_length : int
            Hop length of STFT.
        match_stride : bool
            Whether or not to match stride, making the STFT have the same alignment as
            convolutional layers.

        Returns
        -------
        tuple
            Amount to pad on either side of audio.
        r   z+For match_stride, hop must equal n_fft // 4rT   r   )rj   mathr   )r.   r   r   r   r   	right_padr   r1   r1   r2   compute_stft_paddingA  s   z AudioSignal.compute_stft_paddingr   c                 C   s   |du r| j jnt|}|du r| j jnt|}|du r | j jn|}|du r*| j jn|}|du r4| j jn|}| ||| jj	}|
| jj	}| j}| |||\}}	tjj||	|	| f|}tj|d|jd |||ddd}
|
j\}}}|
| j| j||}
|r|
dddf }
|
| _|
S )a  Computes the short-time Fourier transform of the audio data,
        with specified STFT parameters.

        Parameters
        ----------
        window_length : int, optional
            Window length of STFT, by default ``0.032 * self.sample_rate``.
        hop_length : int, optional
            Hop length of STFT, by default ``window_length // 4``.
        window_type : str, optional
            Type of window to use, by default ``sqrt\_hann``.
        match_stride : bool, optional
            Whether to match the stride of convolutional layers, by default False
        padding_type : str, optional
            Type of padding to use, by default 'reflect'

        Returns
        -------
        torch.Tensor
            STFT of audio data.

        Examples
        --------
        Compute the STFT of an AudioSignal:

        >>> signal = AudioSignal(torch.randn(44100), 44100)
        >>> signal.stft()

        Vary the window and hop length:

        >>> stft_params = [STFTParams(128, 32), STFTParams(512, 128)]
        >>> for stft_param in stft_params:
        >>>     signal.stft_params = stft_params
        >>>     signal.stft()

        Nr   T)n_fftr   r,   return_complexcenter.rT   )r   r   rM   r   r   r   r   r   r'   r   r   r   r#   r   r   r   stftreshaperR   rL   rK   r)   )r.   r   r   r   r   r   r,   r'   r   r   r)   _nfntr1   r1   r2   r   c  sF   .zAudioSignal.stftc                 C   s,  | j du r	td|du r| jjnt|}|du r| jjnt|}|du r)| jjn|}|du r3| jjn|}| ||| j j	}| j j
\}}}	}
| j || |	|
}| |||\}}|du rh| j}|d|  | }|rrtjj|d}tj|||||dd}|||d}|r|d|||  f }|| _| S )	aw  Computes inverse STFT and sets it to audio\_data.

        Parameters
        ----------
        window_length : int, optional
            Window length of STFT, by default ``0.032 * self.sample_rate``.
        hop_length : int, optional
            Hop length of STFT, by default ``window_length // 4``.
        window_type : str, optional
            Type of window to use, by default ``sqrt\_hann``.
        match_stride : bool, optional
            Whether to match the stride of convolutional layers, by default False
        length : int, optional
            Original length of signal, by default None

        Returns
        -------
        AudioSignal
            AudioSignal with istft applied.

        Raises
        ------
        RuntimeError
            Raises an error if stft was not called prior to istft on the signal,
            or if stft_data is not set.
        Nz.Cannot do inverse STFT without self.stft_data!rT   )rT   rT   T)r   r   r,   r   r   r   .)r)   rt   r   r   rM   r   r   r   r   r   rR   r   r   r   r#   r   r   r   istftr'   )r.   r   r   r   r   r   r,   nbnchr   r   r)   r   r   r'   r1   r1   r2   r     sH   
"zAudioSignal.istft        r   r   n_melsfminfmaxc                 C   s   ddl m} || ||||dS )a   Create a Filterbank matrix to combine FFT bins into Mel-frequency bins.

        Parameters
        ----------
        sr : int
            Sample rate of audio
        n_fft : int
            Number of FFT bins
        n_mels : int
            Number of mels
        fmin : float, optional
            Lowest frequency, in Hz, by default 0.0
        fmax : float, optional
            Highest frequency, by default None

        Returns
        -------
        np.ndarray [shape=(n_mels, 1 + n_fft/2)]
            Mel transform matrix
        r   )melr   r   r   r   r   )librosa.filtersr   )r   r   r   r   r   librosa_mel_fnr1   r1   r2   get_mel_filters  s   zAudioSignal.get_mel_filtersP   mel_fminmel_fmaxc           
      K   sv   | j di |}t|}|jd }| j| jd|d  |||d}t|| j}|	dd|j
 }	|		dd}	|	S )a  Computes a Mel spectrogram.

        Parameters
        ----------
        n_mels : int, optional
            Number of mels, by default 80
        mel_fmin : float, optional
            Lowest frequency, in Hz, by default 0.0
        mel_fmax : float, optional
            Highest frequency, by default None
        kwargs : dict, optional
            Keyword arguments to self.stft().

        Returns
        -------
        torch.Tensor [shape=(batch, channels, mels, time)]
            Mel spectrogram.
        rT   r   r   r   Nr1   )r   r#   r\   rR   r   r   r   r   r   	transposer   )
r.   r   r  r  r>   r   	magnituder   	mel_basismel_spectrogramr1   r1   r2   r  5  s   


zAudioSignal.mel_spectrogramorthon_mfccnormc                 C   s   ddl m} || |||S )a  Create a discrete cosine transform (DCT) transformation matrix with shape (``n_mels``, ``n_mfcc``),
        it can be normalized depending on norm. For more information about dct:
        http://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-II

        Parameters
        ----------
        n_mfcc : int
            Number of mfccs
        n_mels : int
            Number of mels
        norm   : str
            Use "ortho" to get a orthogonal matrix or None, by default "ortho"
        device : str, optional
            Device to load the transformation matrix on, by default None

        Returns
        -------
        torch.Tensor [shape=(n_mels, n_mfcc)] T
            The dct transformation matrix.
        r   )
create_dct)torchaudio.functionalr  r   )r	  r   r
  r   r  r1   r1   r2   get_dct[  s   zAudioSignal.get_dct(   ư>
log_offsetc                 K   sR   | j |fi |}t|| }| ||d| j}|dd| }|dd}|S )a{  Computes mel-frequency cepstral coefficients (MFCCs).

        Parameters
        ----------
        n_mfcc : int, optional
            Number of mels, by default 40
        n_mels : int, optional
            Number of mels, by default 80
        log_offset: float, optional
            Small value to prevent numerical issues when trying to compute log(0), by default 1e-6
        kwargs : dict, optional
            Keyword arguments to self.mel_spectrogram(), note that some of them will be used for self.stft()

        Returns
        -------
        torch.Tensor [shape=(batch, channels, mfccs, time)]
            MFCCs.
        r  r   r   )r  r#   logr  r   r  )r.   r	  r   r  r>   r  dct_matmfccr1   r1   r2   r  v  s   zAudioSignal.mfccc                 C      | j du r	|   t| j S )a  Computes and returns the absolute value of the STFT, which
        is the magnitude. This value can also be set to some tensor.
        When set, ``self.stft_data`` is manipulated so that its magnitude
        matches what this is set to, and modulated by the phase.

        Returns
        -------
        torch.Tensor
            Magnitude of STFT.

        Examples
        --------
        >>> signal = AudioSignal(torch.randn(44100), 44100)
        >>> magnitude = signal.magnitude # Computes stft if not computed
        >>> magnitude[magnitude < magnitude.mean()] = 0
        >>> signal.magnitude = magnitude
        >>> signal.istft()
        N)r)   r   r#   r\   r6   r1   r1   r2   r       
zAudioSignal.magnitudec                 C   s   |t d| j  | _d S Ny              ?)r#   expphaser)   r.   r   r1   r1   r2   r             ?h㈵>      T@	ref_valueamintop_dbc                 C   sd   | j }|d }dt|dj|d }|dtt|| 8 }|dur0t|| | }|S )a  Computes the log-magnitude of the spectrogram.

        Parameters
        ----------
        ref_value : float, optional
            The magnitude is scaled relative to ``ref``: ``20 * log10(S / ref)``.
            Zeros in the output correspond to positions where ``S == ref``,
            by default 1.0
        amin : float, optional
            Minimum threshold for ``S`` and ``ref``, by default 1e-5
        top_db : float, optional
            Threshold the output at ``top_db`` below the peak:
            ``max(10 * log10(S/ref)) - top_db``, by default -80.0

        Returns
        -------
        torch.Tensor
            Log-magnitude spectrogram
        rT   g      $@)rv   N)r  r#   log10powclampr!   maximumr;   )r.   r  r  r   r  log_specr1   r1   r2   log_magnitude  s   zAudioSignal.log_magnitudec                 C   r  )aH  Computes and returns the phase of the STFT.
        This value can also be set to some tensor.
        When set, ``self.stft_data`` is manipulated so that its phase
        matches what this is set to, we original magnitudeith th.

        Returns
        -------
        torch.Tensor
            Phase of STFT.

        Examples
        --------
        >>> signal = AudioSignal(torch.randn(44100), 44100)
        >>> phase = signal.phase # Computes stft if not computed
        >>> phase[phase < phase.mean()] = 0
        >>> signal.phase = phase
        >>> signal.istft()
        N)r)   r   r#   angler6   r1   r1   r2   r    r  zAudioSignal.phasec                 C   s   | j td|  | _d S r  )r  r#   r  r)   r  r1   r1   r2   r    r  c                 C   s    |   }| jt|7  _|S r   r   r'   r   
_get_valuer.   other
new_signalr1   r1   r2   __add__     zAudioSignal.__add__c                 C   s   |  j t|7  _ | S r   r'   r   r)  r.   r+  r1   r1   r2   __iadd__     zAudioSignal.__iadd__c                 C   s   | | S r   r1   r0  r1   r1   r2   __radd__     zAudioSignal.__radd__c                 C   s    |   }| jt|8  _|S r   r(  r*  r1   r1   r2   __sub__  r.  zAudioSignal.__sub__c                 C   s   |  j t|8  _ | S r   r/  r0  r1   r1   r2   __isub__   r2  zAudioSignal.__isub__c                 C   s    |   }| jt|9  _|S r   r(  r*  r1   r1   r2   __mul__  r.  zAudioSignal.__mul__c                 C   s   |  j t|9  _ | S r   r/  r0  r1   r1   r2   __imul__	  r2  zAudioSignal.__imul__c                 C   s   | | S r   r1   r0  r1   r1   r2   __rmul__  r4  zAudioSignal.__rmul__c              	   C   sX   | j r| j dnd}| d| j| jr| jnd| j| jr| jnd| jj| j| jd}|S )Nz0.3fz	[unknown]z secondszpath unknown)r   rL   pathr   rK   zaudio_data.shaper   r   )	r   rL   r&   r   rK   r'   rR   r   r   )r.   durr9   r1   r1   r2   _info  s   zAudioSignal._infoc                 C   s<   |   }d}| D ]\}}d| d| d}||7 }q
|S )a  Produces a markdown representation of AudioSignal, in a markdown table.

        Returns
        -------
        str
            Markdown representation of AudioSignal.

        Examples
        --------
        >>> signal = AudioSignal(torch.randn(44100), 44100)
        >>> print(signal.markdown())
        | Key | Value
        |---|---
        | duration | 1.000 seconds |
        | batch_size | 1 |
        | path | path unknown |
        | sample_rate | 44100 |
        | num_channels | 1 |
        | audio_data.shape | torch.Size([1, 1, 44100]) |
        | stft_params | STFTParams(window_length=2048, hop_length=512, window_type='sqrt_hann', match_stride=False) |
        | device | cpu |
        z| Key | Value 
|---|--- 
z| z | z |
r<  items)r.   r9   FORMATkvrowr1   r1   r2   markdown   s   
zAudioSignal.markdownc                 C   s6   |   }d}| D ]\}}|| d| d7 }q
|S )N : 
r=  )r.   r9   descr@  rA  r1   r1   r2   __str__?  s
   zAudioSignal.__str__c                 C   sf   ddl m} |  }|| jj d}|jddd |jddd | D ]\}}||t| q$|S )	Nr   )Table)titleKeygreen)styleValuecyan)	
rich.tablerI  r<  	__class____name__
add_columnr>  add_rowr   )r.   rI  r9   tabler@  rA  r1   r1   r2   __rich__G  s   zAudioSignal.__rich__c                 C   sl   t | j D ],\}}t|r3tj||j| dds3||j|    }td| d|   dS qdS )Nr  )atolzMax abs error for rE  FT)	list__dict__r>  r#   r$   allcloser\   r;   print)r.   r+  r@  rA  	max_errorr1   r1   r2   __eq__U  s   
zAudioSignal.__eq__c                 C   s   t |r!|jdkr!| du r!| jdksJ | j}| j}| j}n1t|t	t
tttfs5t |rR|jdkrR| j| }| jd urD| j| nd }| jd urP| j| nd }d }t| || j| jd}||_||_||_|S )Nr   Tr   r   )r#   r$   r   itemrL   r'   r   r)   r   boolrM   rX  slicetupler   r   r   r   r(   )r.   r   r'   r   r)   r(   r   r1   r1   r2   __getitem___  s$    

zAudioSignal.__getitem__c                 C   s   t |t| s|| j|< d S t|r3|jdkr3| du r3| jdks%J |j| _|j| _|j	| _	d S t |t
ttttfsGt|ry|jdkr{| jd urW|jd urW|j| j|< | jd urg|jd urg|j| j|< | j	d urw|j	d urw|j	| j	|< d S d S d S )Nr   Tr   )r   r   r'   r#   r$   r   r^  rL   r   r)   r_  rM   rX  r`  ra  )r.   r   r   r1   r1   r2   __setitem__z  s,   
 
zAudioSignal.__setitem__c                 C   s
   | |k S r   r1   r0  r1   r1   r2   __ne__  s   
zAudioSignal.__ne__)NNr   NN)NNN)NrD   N)r   r   )r   rP   )FFFr   )r   )r   r   )r   N)r  r   N)r  N)r  r  r  )r  r  r  )YrR  
__module____qualname____doc__typingUnionr#   Tensorr   r   r!   r"   rM   r   r   r3   propertyr7   classmethodrandomRandomStaterC   rJ   rN   rc   rX  r_  r   r*   r+   r   r   r   r   r   r   r   rg   r   r   r   r   ru   r   r   rw   r   r'   settersamplesr)   rL   rj   r   rR   r   r   rK   staticmethod	functools	lru_cacher   r   r   r   r   r   r  r  r  r  r&  r  r-  r1  r3  r5  r6  r7  r8  r9  r<  rC  rH  rV  r]  rb  rc  rd  r1   r1   r1   r2   r   5   s   
>
/
	/<%5a
9
()


		













$
]
T"
& 



 


r   )%r   rr  r   r   r    r   rh  r   collectionsr   r   r   r   r!   r   r#   rD  r   displayr   dspr   effectsr   r	   ffmpegr
   rH   r   playbackr   whisperr   r   __new____defaults__r   r1   r1   r1   r2   <module>   sN    
