o
    siS/                  
   @   sl   d dl Z d dl mZ ddlmZ G dd de jjZde jde jd	ed
edef
ddZG dd dejZ	dS )    N)nn   )
PITReorderc                       sN   e Zd ZdZ				d fdd	Zdd	 Zd
d Zedd Zdd Z	  Z
S )LambdaOverlapAddaN  Overlap-add with lambda transform on segments (not scriptable).

    Segment input signal, apply lambda function (a neural network for example)
    and combine with OLA.

    `LambdaOverlapAdd` can be used with :mod:`asteroid.separate` and the
    `asteroid-infer` CLI.

    Args:
        nnet (callable): Function to apply to each segment.
        n_src (Optional[int]): Number of sources in the output of nnet.
            If None, the number of sources is determined by the network's output,
            but some correctness checks cannot be performed.
        window_size (int): Size of segmenting window.
        hop_size (int): Segmentation hop size.
        window (str): Name of the window (see scipy.signal.get_window) used
            for the synthesis.
        reorder_chunks (bool): Whether to reorder each consecutive segment.
            This might be useful when `nnet` is permutation invariant, as
            source assignements might change output channel from one segment
            to the next (in classic speech separation for example).
            Reordering is performed based on the correlation between
            the overlapped part of consecutive segment.

     Examples
        >>> from asteroid import ConvTasNet
        >>> nnet = ConvTasNet(n_src=2)
        >>> continuous_nnet = LambdaOverlapAdd(
        >>>     nnet=nnet,
        >>>     n_src=2,
        >>>     window_size=64000,
        >>>     hop_size=None,
        >>>     window="hanning",
        >>>     reorder_chunks=True,
        >>>     enable_grad=False,
        >>> )

        >>> # Process wav tensor:
        >>> wav = torch.randn(1, 1, 500000)
        >>> out_wavs = continuous_nnet.forward(wav)
        >>> # asteroid.separate.Separatable support:
        >>> from asteroid.separate import file_separate
        >>> file_separate(continuous_nnet, "example.wav")
    NhannTFc           	         s   t    |d dksJ d|| _|| _|d ur|n|d | _|| _t|dd | _|rDddlm	} ||| j
d}t|}d| _nd| _| d	| || _|| _d S )
Nr   r   zWindow size must be evenin_channels)
get_windowfloat32TFwindow)super__init__nnetwindow_sizehop_sizen_srcgetattrr   scipy.signalr   astypetorch
from_numpy
use_windowregister_bufferreorder_chunksenable_grad)	selfr   r   r   r   r
   r   r   r   	__class__ L/home/ubuntu/.local/lib/python3.10/site-packages/asteroid/dsp/overlap_add.pyr   4   s    



zLambdaOverlapAdd.__init__c                 C   s  |j dksJ | \}}}tjjj|d| jdf| jdf| jdfd}g }|j	d }t
|D ]b}| |d|f }	|dkr^|	j dksHJ d| jdurY|	j	d | jksYJ d|	j	d }
|	||
 d}	|dkry| jryt|	|d |
| j| j}	| jr|	| j|	 }	n|	| j| j  }	||	 q0t||||
 | j}|dd	d}tjjj||df| jdf| jdf| jdfd}|d||
dS )
zAHeart of the class: segment signal, apply func, combine with OLA.      r   kernel_sizepaddingstride.z'nnet should return (batch, n_src, time)Nr   )ndimsizer   r   
functionalunfold	unsqueezer   r   shaperanger   r   reshaper   _reorder_sourcesr   r
   toappendstackpermutefoldsqueeze)r   xbatchchannelsn_framesunfoldedoutn_chunks	frame_idxframer   r   r   r   ola_forwardT   sD   


zLambdaOverlapAdd.ola_forwardc                 C   s@   t j| j | |}|W  d   S 1 sw   Y  dS )zForward module: segment signal, apply func, combine with OLA.

        Args:
            x (:class:`torch.Tensor`): waveform signal of shape (batch, 1, time).

        Returns:
            :class:`torch.Tensor`: The output of the lambda OLA.
        N)r   autogradset_grad_enabledr   r>   )r   r5   oladr   r   r   forward   s   

$zLambdaOverlapAdd.forwardc                 C   s   | j jS N)r   sample_rate)r   r   r   r   rD      s   zLambdaOverlapAdd.sample_ratec                 O   s   | j |g|R i |S rC   )rB   )r   wavargskwargsr   r   r   	_separate   s   zLambdaOverlapAdd._separate)Nr   TF)__name__
__module____qualname____doc__r   r>   rB   propertyrD   rH   __classcell__r   r   r   r   r      s    2 1
r   currentpreviousr   r   r   c           	         sZ   |   \}}| d||} |d||}||   fdd}t|}|| |} | ||S )a  
     Reorder sources in current chunk to maximize correlation with previous chunk.
     Used for Continuous Source Separation. Standard dsp correlation is used
     for reordering.


    Args:
        current (:class:`torch.Tensor`): current chunk, tensor
                                        of shape (batch, n_src, window_size)
        previous (:class:`torch.Tensor`): previous chunk, tensor
                                        of shape (batch, n_src, window_size)
        n_src (:class:`int`): number of sources.
        window_size (:class:`int`): window_size, equal to last dimension of
                                    both current and previous.
        hop_size (:class:`int`): hop_size between current and previous tensors.

    r    c                    sf   | dd  f } |d  d f }| | j ddd } ||j ddd }tj| d|d dd S )N.r    T)keepdimr!   r   )dim)meanr   sumr*   )r5   y	overlap_fr   r   reorder_func   s
    z&_reorder_sources.<locals>.reorder_func)r'   r-   r   )	rO   rP   r   r   r   r6   framesrX   pitr   rV   r   r.      s   

r.   c                       sJ   e Zd ZdZ fddZdd ZdddZed	d
 Zedd Z	  Z
S )DualPathProcessinga  
    Perform Dual-Path processing via overlap-add as in DPRNN [1].

    Args:
        chunk_size (int): Size of segmenting window.
        hop_size (int): segmentation hop size.

    References
        [1] Yi Luo, Zhuo Chen and Takuya Yoshioka. "Dual-path RNN: efficient
        long sequence modeling for time-domain single-channel speech separation"
        https://arxiv.org/abs/1910.06379
    c                    s$   t t|   || _|| _d | _d S rC   )r   r[   r   
chunk_sizer   n_orig_frames)r   r\   r   r   r   r   r      s   
zDualPathProcessing.__init__c                 C   sh   |  \}}}|jdksJ |jd | _tjjj|d| j	df| j	df| j
dfd}|||| j	dS )ar  
        Unfold the feature tensor from $(batch, channels, time)$ to
        $(batch, channels, chunksize, nchunks)$.

        Args:
            x (:class:`torch.Tensor`): feature tensor of shape $(batch, channels, time)$.

        Returns:
            :class:`torch.Tensor`: spliced feature tensor of shape
            $(batch, channels, chunksize, nchunks)$.

        r   r    r!   r   r"   )r'   r&   r+   r]   r   r   r(   r)   r*   r\   r   r-   )r   r5   r6   chanrY   r9   r   r   r   r)      s   
zDualPathProcessing.unfoldNc                 C   s   |dur|n| j }| \}}}}|||| j |}tjjj||df| jdf| jdf| jdfd}|t	| j| j  }|||| j S )a  
        Folds back the spliced feature tensor.
        Input shape $(batch, channels, chunksize, nchunks)$ to original shape
        $(batch, channels, time)$ using overlap-add.

        Args:
            x (:class:`torch.Tensor`): spliced feature tensor of shape
                $(batch, channels, chunksize, nchunks)$.
            output_size (int, optional): sequence length of original feature tensor.
                If None, the original length cached by the previous call of
                :meth:`unfold` will be used.

        Returns:
            :class:`torch.Tensor`:  feature tensor of shape $(batch, channels, time)$.

        .. note:: `fold` caches the original length of the input.

        Nr!   r   r"   )
r]   r'   r-   r\   r   r   r(   r3   r   float)r   r5   output_sizer6   r^   r\   r;   	to_unfoldr   r   r   r3      s   	zDualPathProcessing.foldc                 C   s^   |   \}}}}| dd|| ||dd} || } | ||||dddd} | S )a_  Performs intra-chunk processing.

        Args:
            x (:class:`torch.Tensor`): spliced feature tensor of shape
                (batch, channels, chunk_size, n_chunks).
            module (:class:`torch.nn.Module`): module one wish to apply to each chunk
                of the spliced feature tensor.

        Returns:
            :class:`torch.Tensor`: processed spliced feature tensor of shape
            $(batch, channels, chunksize, nchunks)$.

        .. note:: the module should have the channel first convention and accept
            a 3D tensor of shape $(batch, channels, time)$.
        r!   r    r   r'   	transposer-   r5   moduler6   r7   r\   r;   r   r   r   intra_process  s
   " z DualPathProcessing.intra_processc                 C   sN   |   \}}}}| dd|| ||} || } | ||||dd} | S )ai  Performs inter-chunk processing.

        Args:
            x (:class:`torch.Tensor`): spliced feature tensor of shape
                $(batch, channels, chunksize, nchunks)$.
            module (:class:`torch.nn.Module`): module one wish to apply between
                each chunk of the spliced feature tensor.


        Returns:
            x (:class:`torch.Tensor`): processed spliced feature tensor of shape
            $(batch, channels, chunksize, nchunks)$.

        .. note:: the module should have the channel first convention and accept
            a 3D tensor of shape $(batch, channels, time)$.
        r!   r   rb   rd   r   r   r   inter_process8  s
   z DualPathProcessing.inter_processrC   )rI   rJ   rK   rL   r   r)   r3   staticmethodrf   rg   rN   r   r   r   r   r[      s    
$
r[   )
r   r   losses.pit_wrapperr   Moduler   FloatTensorintr.   r[   r   r   r   r   <module>   s"     
-