o
    ¡¿¯iH  ã                   @   s²   d Z ddlZddlZ	d+dd	„Zd,d
d„Zd-dd„Zd.dd„Z			d/dd„Zdd„ Zdd„ Z	dd„ Z
dd„ Z	d0dd„Zdd„ Zd d!„ Zd"d#„ Zd$d%„ Zd&d'„ Z	)d1d*d(„ZdS )2a  
This implementation is modified from https://github.com/zcaceres/spec_augment

MIT License

Copyright (c) 2019 Zach Caceres

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETjjHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
é    Né   é   é(   é   Fc                 C   s$   t tt| |d|||d|||dS )a¥  SpecAugment

    Reference:
        SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition
        (https://arxiv.org/pdf/1904.08779.pdf)

    This implementation modified from https://github.com/zcaceres/spec_augment

    :param torch.Tensor spec: input tensor with the shape (T, dim)
    :param int W: time warp parameter
    :param int F: maximum width of each freq mask
    :param int T: maximum width of each time mask
    :param int num_freq_masks: number of frequency masks
    :param int num_time_masks: number of time masks
    :param bool replace_with_zero: if True, masked parts will be filled with 0,
        if False, filled with mean
    )ÚW)ÚFÚ	num_masksÚreplace_with_zero)ÚTr   r	   )Ú	time_maskÚ	freq_maskÚ	time_warp)Úspecr   r   r
   Únum_freq_masksÚnum_time_masksr	   © r   úM/home/ubuntu/.local/lib/python3.10/site-packages/espnet/utils/spec_augment.pyÚspecaug"   s   
ü÷r   c                 C   sÒ   |   d¡} | jd }| jd }| j}|d }| ddd…|f }t|ƒ|ks'J ‚|t ||| ¡ }t|tjƒs9J ‚t | |¡}tj	||ggg|dtj	|| |ggg|d}	}
t
| |	|
ƒ\}}| d¡ d¡S )zwTime warping

    :param torch.Tensor spec: input tensor with shape (T, dim)
    :param int W: time warp parameter
    r   é   r   N©Údeviceé   )Ú	unsqueezeÚshaper   ÚlenÚrandomÚ	randrangeÚ
isinstanceÚtorchÚTensorÚtensorÚsparse_image_warpÚsqueeze)r   r   Úspec_lenÚnum_rowsr   ÚyÚhorizontal_line_at_ctrÚpoint_to_warpÚdist_to_warpÚsrc_ptsÚdest_ptsÚwarped_spectroÚdense_flowsr   r   r   r   C   s   


þr   r   c           
      C   s²   |   d¡ ¡ }|jd }td|ƒD ]B}t d|¡}t d|| ¡}||| kr.| d¡  S t ||| ¡}	|rEd|d dd…||	…f< q| ¡ |d dd…||	…f< q| d¡S )a   Frequency masking

    :param torch.Tensor spec: input tensor with shape (T, dim)
    :param int F: maximum width of each mask
    :param int num_masks: number of masks
    :param bool replace_with_zero: if True, masked parts will be filled with 0,
        if False, filled with mean
    r   r   N©r   Úcloner   Úranger   r   r"   Úmean)
r   r   r   r	   ÚclonedÚnum_mel_channelsÚiÚfÚf_zeroÚmask_endr   r   r   r   _   ó   	

r   c           
      C   s²   |   d¡ ¡ }|jd }td|ƒD ]B}t d|¡}t d|| ¡}||| kr.| d¡  S t ||| ¡}	|rEd|d ||	…dd…f< q| ¡ |d ||	…dd…f< q| d¡S )a  Time masking

    :param torch.Tensor spec: input tensor with shape (T, dim)
    :param int T: maximum width of each mask
    :param int num_masks: number of masks
    :param bool replace_with_zero: if True, masked parts will be filled with 0,
        if False, filled with mean
    r   r   Nr-   )
r   r
   r   r	   r1   Úlen_spectror3   ÚtÚt_zeror6   r   r   r   r   {   r7   r   ç        c                 C   sV   | j }|| }| j\}}	}
t|	|
|ƒ}t|||||ƒ}t|||	|
ƒ}t| |ƒ}||fS ©N)r   r   Úget_flat_grid_locationsÚinterpolate_splineÚcreate_dense_flowsÚdense_image_warp)Ú
img_tensorÚsource_control_point_locationsÚdest_control_point_locationsÚinterpolation_orderÚregularization_weightÚnum_boundaries_pointsr   Úcontrol_point_flowsÚ
batch_sizeÚimage_heightÚimage_widthÚflattened_grid_locationsÚflattened_flowsr,   Úwarped_imager   r   r   r!   —   s$   ÿûÿ
r!   c                 C   sL   t jd| d | |d}t jd|d ||d}t  ||¡\}}t  ||fd¡S )Nr   r   r   éÿÿÿÿ)r   ÚlinspaceÚmeshgridÚstack©rI   rJ   r   Úy_rangeÚx_rangeÚy_gridÚx_gridr   r   r   Úget_grid_locations¸   s   rW   c                 C   s   t  | || dg¡S ©Nr   ©r   Úreshape)Úgrid_locationsrI   rJ   r   r   r   Úflatten_grid_locations¿   s   r\   c                 C   sZ   t jd| d | |d}t jd|d ||d}t  ||¡\}}t  ||fd¡ | | dg¡S )Nr   r   r   rN   r   )r   rO   rP   rQ   rZ   rR   r   r   r   r=   Ã   s   r=   c                 C   s   t  | |||dg¡S rX   rY   )rL   rH   rI   rJ   r   r   r   r?   Ê   s   r?   c                 C   s&   t | |||ƒ\}}t|| |||ƒ}|S r<   )Úsolve_interpolationÚapply_interpolation)Útrain_pointsÚtrain_valuesÚquery_pointsÚorderrE   ÚwÚvÚquery_valuesr   r   r   r>   Ï   s   r>   c                 C   sF  | j }| j\}}}|jd }| }	| ¡ }
tt|	|	ƒ|ƒ d¡}tjd| j|d 	g d¢¡}t 
|	|fd¡ ¡ }t 
|t |dd¡fd¡}|jd }tj|||f|dd }t 
||fd¡}t 
||fd¡}tj||d |f| j|d ¡ }t 
|
|fd¡}t ||¡\}}|d d …d |…d d …f }|d d …|d …d d …f }||fS )	NrN   r   r   ©Údtyper   )rN   r   r   r   r   g    _ B)r   r   ÚfloatÚphiÚcross_squared_distance_matrixr   r   Úonesrg   ÚviewÚcatÚ	transposeÚrandnÚzerosÚgesv)r_   r`   rb   rE   r   ÚbÚnÚdÚkÚcr4   Úmatrix_ark   Úmatrix_bÚ
left_blockÚ
num_b_colsÚ	lhs_zerosÚright_blockÚlhsÚ	rhs_zerosÚrhsÚXÚLUrc   rd   r   r   r   r]   Þ   s.   

ÿþr]   c                 C   s\   t  t  | | ¡¡}t  t  ||¡¡}t  |  d¡| d¡ dd¡¡}|d|  | }| ¡ S )ak  Pairwise squared distance between two (batch) matrices' rows (2nd dim).

    Computes the pairwise distances between rows of x and rows of y
    Args:
    x: [batch_size, n, d] float `Tensor`
    y: [batch_size, m, d] float `Tensor`
    Returns:
    squared_dists: [batch_size, n, m] float `Tensor`, where
    squared_dists[b,i,j] = ||x[b,i,:] - y[b,j,:]||^2
    r   r   r   )r   ÚsumÚmulÚmatmulr"   rn   rh   )Úxr%   Úx_norm_squaredÚy_norm_squaredÚx_y_transposeÚsquared_distsr   r   r   rj     s
    rj   c                 C   sÎ   t jd| jd}|dkrt  | |¡} t  | ¡} | S |dkr*d|  t  t  | |¡¡ S |dkr>dt  | ¡ t  t  | |¡¡ S |d dkrYt  | |¡} dt  | d| ¡ t  | ¡ S t  | |¡} t  | d| ¡S )a  Coordinate-wise nonlinearity used to define the order of the interpolation.

    See https://en.wikipedia.org/wiki/Polyharmonic_spline for the definition.
    Args:
    r: input op
    order: interpolation order
    Returns:
    phi_k evaluated coordinate-wise on r, for k = r
    g»½×Ùß|Û=r   r   r   g      à?é   r   )r   r    r   ÚmaxÚsqrtÚlogÚsquareÚpow)Úrrb   ÚEPSILONr   r   r   ri     s   

 ri   c                 C   sp   |   d¡} t|  ¡ | ¡ ƒ}t||ƒ}t ||¡}t | ddd…f ¡}t | |fd¡ ¡ }	t |	|¡}
||
 S )a¥  Apply polyharmonic interpolation model to data.

    Notes:
        Given coefficients w and v for the interpolation model, we evaluate
        interpolated function values at query_points.

    Args:
        query_points: `[b, m, d]` x values to evaluate the interpolation at
        train_points: `[b, n, d]` x values that act as the interpolation centers
            ( the c variables in the wikipedia article)
            w: `[b, n, k]` weights on each interpolation center
            v: `[b, d, k]` weights on each input dimension
        order: order of the interpolation

    Returns:
        Polyharmonic interpolation evaluated at points defined in query_points.
    r   .Nr   r   )r   rj   rh   ri   r   r„   Ú	ones_likerm   )ra   r_   rc   rd   rb   Úpairwise_distsÚphi_pairwise_distsÚrbf_termrk   Úquery_points_padÚlinear_termr   r   r   r^   9  s   
ÿ
r^   c                 C   s®   |   d¡} | j\}}}}| j}t tj||dtj||d¡\}}tj||fdd ¡ }	|	  d¡ dddd¡}
|
| }t 	|||| dg¡}t
| |ƒ}t 	|||||g¡}|S )a  Image warping using per-pixel flow vectors.

    Apply a non-linear warp to the image, where the warp is specified by a dense
    flow field of offset vectors that define the correspondences of pixel values
    in the output image back to locations in the  source image. Specifically, the
    pixel value at output[b, j, i, c] is
    images[b, j - flow[b, j, i, 0], i - flow[b, j, i, 1], c].
    The locations specified by this formula do not necessarily map to an int
    index. Therefore, the pixel value is obtained by bilinear
    interpolation of the 4 nearest pixels around
    (b, j - flow[b, j, i, 0], i - flow[b, j, i, 1]). For locations outside
    of the image, we use the nearest pixel values at the image boundary.
    Args:
    image: 4-D float `Tensor` with shape `[batch, height, width, channels]`.
    flow: A 4-D float `Tensor` with shape `[batch, height, width, 2]`.
    name: A name for the operation (optional).
    Note that image and flow can be of type tf.half, tf.float32, or tf.float64,
    and do not necessarily have to be the same type.
    Returns:
    A 4-D float `Tensor` with shape`[batch, height, width, channels]`
    and same type as input image.
    Raises:
    ValueError: if height < 2 or width < 2 or the inputs have the wrong number
    of dimensions.
    r   r   r   )ÚdimrN   r   r   )r   r   r   r   rP   ÚarangerQ   rh   ÚpermuterZ   Úinterpolate_bilinear)ÚimageÚflowrH   ÚheightÚwidthÚchannelsr   Úgrid_xÚgrid_yÚstacked_gridÚbatched_gridÚquery_points_on_gridÚquery_points_flattenedÚinterpolatedr   r   r   r@   ]  s   
ÿÿ
r@   r›   Úijc           #         sf  |dkr|dkrt dƒ‚| j}t|ƒdkr d}t |t| jƒ ƒ‚| j\‰}‰‰ˆ|ˆˆg}|j}| j}| j}	|jd ‰g }
g }g }|dkrIddgnddg}| d¡}|D ]n}|| }||d  }tj|d ||	d	}tjd
||	d	}t 	|t 
|¡¡}t ||¡}| ¡ }| |¡ |d }| |¡ tj|| ||	d	}tjd
||	d	}tjd||	d	}t t 	||¡|¡}t |d¡}|
 |¡ qTt | ˆ| ˆ ˆg¡‰t tjˆ|	d| ˆ ˆdg¡‰ ‡ ‡‡‡‡‡fdd„}||d |d dƒ}||d |d dƒ}||d |d dƒ}||d |d dƒ}|
d ||  | } |
d ||  | }!|
d |!|   |  }"|"S )a¡  Similar to Matlab's interp2 function.

    Notes:
        Finds values for query points on a grid using bilinear interpolation.

    Args:
        grid: a 4-D float `Tensor` of shape `[batch, height, width, channels]`.
        query_points: a 3-D float `Tensor` of N points with shape `[batch, N, 2]`.
        name: a name for the operation (optional).
        indexing: whether the query points are specified as row and column (ij),
            or Cartesian coordinates (xy).

    Returns:
        values: a 3-D `Tensor` with shape `[batch, N, channels]`

    Raises:
        ValueError: if the indexing mode is invalid, or if the shape of the inputs
        invalid.
    r¨   Úxyz"Indexing mode must be 'ij' or 'xy'rŠ   z+Grid must be 4 dimensional. Received size: r   r   r   rf   r;   g      ð?r   c                    s4   ˆ | ˆ  | }t  ˆ ¡ d|¡}t  |ˆˆˆg¡S )Nr   )r   Úgatherr9   rZ   )Úy_coordsÚx_coordsÚnameÚlinear_coordinatesÚgathered_values©Úbatch_offsetsrH   r    Úflattened_gridÚnum_queriesrŸ   r   r   rª   å  s   z$interpolate_bilinear.<locals>.gatherÚtop_leftÚ	top_rightÚbottom_leftÚbottom_right)Ú
ValueErrorr   r   Ústrrg   r   Úunbindr   r    r‹   ÚfloorÚminÚlongÚappendr   rZ   r™   )#Úgridra   r­   Úindexingr   Úmsgrž   Ú
query_typeÚ	grid_typeÚgrid_deviceÚalphasÚfloorsÚceilsÚindex_orderÚunstacked_query_pointsr˜   ÚqueriesÚsize_in_indexing_dimensionÚ	max_floorÚ	min_floorÚmaxxr»   Ú	int_floorÚceilÚalphaÚ	min_alphaÚ	max_alpharª   r´   rµ   r¶   r·   Ú
interp_topÚinterp_bottomÚinterpr   r°   r   r›     sb   


ÿ

ÿ)r   r   r   r   r   F)r   )r   r   F)r   r   F)r   r;   r   )r;   )r›   r¨   )Ú__doc__r   r   r   r   r   r   r!   rW   r\   r=   r?   r>   r]   rj   ri   r^   r@   r›   r   r   r   r   Ú<module>   s2   
ÿ
!

 
ú!

û($4ÿ