o
    i-                     @   s   d dl mZ d dlmZmZmZmZm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mZ d dlmZ d d	lmZ eejed
kZG dd deZdS )    )OrderedDict)DictListOptionalTupleUnionN)parse)STFTDecoder)STFTEncoder)tik_reg	to_double)TCNDenseUNet)AbsSeparatorz1.9.0c                       s   e Zd ZdZ												
						d! fdd	Zedd Zedd Zedd Z	d"de	e
j de
jdee deee	e
j  e
jef fddZedd  Z  ZS )#iNeuBea  iNeuBe, iterative neural/beamforming enhancement

    Reference:
    Lu, Y. J., Cornell, S., Chang, X., Zhang, W., Li, C., Ni, Z., ... & Watanabe, S.
    Towards Low-Distortion Multi-Channel Speech Enhancement:
    The ESPNET-Se Submission to the L3DAS22 Challenge. ICASSP 2022 p. 9201-9205.

    NOTES:
    As outlined in the Reference, this model works best when coupled with
    the MultiResL1SpecLoss defined in criterions/time_domain.py.
    The model is trained with variance normalized mixture input and target.
    e.g. with mixture of shape [batch, microphones, samples] you normalize
    it by dividing with torch.std(mixture, (1, 2)). You must do the same
    for the target signal.
    In the Reference, the variance normalization was performed offline
    (we normalized by the std computed on the entire training set and not
    for each input separately). However we found out that also normalizing
    each input and target separately works well.


    Args:
        n_spk: number of output sources/speakers.
        n_fft: stft window size.
        stride: stft stride.
        window: stft window type choose between 'hamming', 'hanning' or None.
        mic_channels: number of microphones channels
            (only fixed-array geometry supported).
        hid_chans: number of channels in the subsampling/upsampling conv layers.
        hid_chans_dense: number of channels in the densenet layers
            (reduce this to reduce VRAM requirements).
        ksz_dense: kernel size in the densenet layers thorough iNeuBe.
        ksz_tcn: kernel size in the TCN submodule.
        tcn_repeats: number of repetitions of blocks in the TCN submodule.
        tcn_blocks: number of blocks in the TCN submodule.
        tcn_channels: number of channels in the TCN submodule.
        activation: activation function to use in the whole iNeuBe model,
            you can use any torch supported activation e.g. 'relu' or 'elu'.
        output_from: output the estimate from 'dnn1', 'mfmcwf' or 'dnn2'.
        n_chunks: number of future and past frames to consider for mfMCWF computation.
        freeze_dnn1: whether or not freezing dnn1 parameters during training of dnn2.
        tik_eps: diagonal loading in the mfMCWF computation.
             hann       r   r           eludnn1F:0yE>c                    s   t    || _|| _|| _|| _|| _|d d }ts J dt||||d| _	t
||||d| _t|||||||	|
|||d| _td||d ||||	|
|||d| _d S )N   r   zHiNeuBe model requires torch>=1.9.0, please install latest torch version.)window)
activation)super__init__n_spkoutput_fromn_chunksfreeze_dnn1tik_epsis_torch_1_9_plusr
   encr	   decr   r   dnn2)selfr"   n_fftstrider   mic_channels	hid_chanshid_chans_dense	ksz_denseksz_tcntcn_repeats
tcn_blockstcn_channelsr   r#   r$   r%   r&   fft_c_channels	__class__ Z/home/ubuntu/.local/lib/python3.10/site-packages/espnet2/enh/separator/ineube_separator.pyr!   <   sL   
ziNeuBe.__init__c                 C   s   | j \}}}|dkr| S tjjjtjjj| ||fdddd| d dfddd	}|j d }|||d| d |}|dd}|S )
a7  unfolding STFT representation to add context in the mics channel.

        Args:
            mixture (torch.Tensor): 3D tensor (monaural complex STFT)
                of shape [B, T, F] batch, frames, microphones, frequencies.
            n_chunks (int): number of past and future to consider.

        Returns:
            est_unfolded (torch.Tensor): complex 3D tensor STFT with context channel.
                shape now is [B, T, C, F] batch, frames, context, frequencies.
                Basically same shape as a multi-channel STFT with C microphones.

        r   constant)moder   r   )r   r   )r   r   )kernel_sizepaddingr-   )	shapetorchnn
functionalunfoldpad	unsqueezereshape	transpose)tf_rep
chunk_sizebszfreq_est_unfoldedr$   r9   r9   r:   rD   {   s    

ziNeuBe.unfoldc              	   C   s   |  dddd} |dd}| j\}}}}t| || d||||d| d  d|}t|}t|}	td||		 }
td||	 }t
t| dddd| dddd}td	||
}td
|	 |}|| }|ddS )a  multi-frame multi-channel wiener filter.

        Args:
            mixture (torch.Tensor): multi-channel STFT complex mixture tensor,
                of shape [B, T, C, F] batch, frames, microphones, frequencies.
            estimate (torch.Tensor): monaural STFT complex estimate
                of target source [B, T, F] batch, frames, frequencies.
            n_chunks (int): number of past and future mfMCWF frames.
                If 0 then standard MCWF.
            tik_eps (float): diagonal loading for matrix inversion in MCWF computation.

        Returns:
            beamformed (torch.Tensor): monaural STFT complex estimate
                of target source after MFMCWF [B, T, F] batch, frames, frequencies.
        r   r   r   r   r=   zbmft, bft->bmfzbmft, bnft->bmnfzbmnf, bnf->bmfz...mf,...mft->...ft)permuterH   r@   r   rD   rG   r   rA   einsumconjinverser   to)mixtureestimater$   r&   rK   micsrM   framesmix_unfolded	estimate1zetascm_mixinv_scm_mix	bf_vector
beamformedr9   r9   r:   mfmcwf   s*   
ziNeuBe.mfmcwfc                 C   s"   t jj| d|| jd  f} | S )Nr   r=   )rA   rB   rC   rE   r@   )input_tensor
target_lenr9   r9   r:   pad2   s   ziNeuBe.pad2Ninputilens
additionalreturnc                    s&  |j \}}}| ||d }| |}| jr| }|j \}	}	}
}| ||| j |
||d  |  || jd|  fddt	 j d D  t
 }| jdkrX ||fS | jdv r |d< t|||| j |
|| j| j|| j|
|}| ||| j |
||d | || jd|| jdkrfd	dt	j d D ||fS | jd
kr |d< |d< | t|| jddd||| j |
|d||| j |
|dfd}| |dddf |d | || jd|fddt	j d D ||fS tt)a  Forward.

        Args:
            input (torch.Tensor): batched multi-channel audio tensor with
                    C audio channels and T samples [B, T, C]
            ilens (torch.Tensor): input lengths [Batch]
            additional (Dict or None): other data, currently unused in this model.

        Returns:
            enhanced (List[Union(torch.Tensor)]):
                    [(B, T), ...] list of len n_spk
                    of mono audio tensors with T samples.
            ilens (torch.Tensor): (B,)
                others predicted data, e.g. masks: OrderedDict[
                    'mask_spk1': torch.Tensor(Batch, Frames, Freq),
                    'mask_spk2': torch.Tensor(Batch, Frames, Freq),
                    ...
                    'mask_spkn': torch.Tensor(Batch, Frames, Freq),
                ]
            additional (Dict or None): other data, currently unused in this model,
                    we return it also in output.
        r   r=   c                       g | ]
} d d |f qS Nr9   .0src)output_dnn1r9   r:   
<listcomp>       z"iNeuBe.forward.<locals>.<listcomp>r   r   )r`   r*   r`   c                    rh   ri   r9   rj   )output_mfmcwfr9   r:   rn     ro   r*   beamr   Nc                    rh   ri   r9   rj   )output_dnn2r9   r:   rn   "  ro   )r@   r(   r   r%   detachr)   rG   num_spkrc   ranger   r#   r   r`   r"   r$   r&   r*   rA   catrepeatrF   NotImplementedError)r+   rd   re   rf   rK   mixture_lenrW   mix_stftest_dnn1rM   rX   rL   others
est_mfmcwfest_dnn2r9   )rm   rr   rp   r:   forward   s   



	ziNeuBe.forwardc                 C   s   | j S ri   )r"   )r+   r9   r9   r:   rt   +  s   ziNeuBe.num_spk)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   Fr   ri   )__name__
__module____qualname____doc__r!   staticmethodrD   r`   rc   r   rA   Tensorr   r   r   r   r   r   propertyrt   __classcell__r9   r9   r7   r:   r      sL    -?

'


ar   )collectionsr   typingr   r   r   r   r   rA   packaging.versionr   V espnet2.enh.decoder.stft_decoderr	    espnet2.enh.encoder.stft_encoderr
   espnet2.enh.layers.beamformerr   r   espnet2.enh.layers.tcndenseunetr   #espnet2.enh.separator.abs_separatorr   __version__r'   r   r9   r9   r9   r:   <module>   s    