o
    8wi͍                     @   s  d 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	Z	ddl
ZddlmZ ddlZddlZddlZdd Z	dRddZdSd
dZdd Zdd ZdTddZ				dUddZdd ZdVddZdVdefddZdd Zdd  Zed!Z d"d# Z!d$d% Z"d&d' Z#d(d) Z$dWd,d-Z%d.d/ Z&d0d1 Z'd2d3 Z(d4d5 Z)	dXd6d7Z*d8d9 Z+		dYd:d;Z,dZd<d=Z-d>d? Z.d@dA Z/dBdC Z0d[dDdEZ1d[dFdGZ2d[dHdIZ3d[dJdKZ4d[dLdMZ5dNdO Z6dPdQ Z7dS )\zThis library gathers utilities for data io operation.

Authors
 * Mirco Ravanelli 2020
 * Aku Rouhe 2020
 * Samuele Cornell 2020
 * Adel Moumen 2024
 * Pierre Champion 2023
    N)Numberc                 C   sT   | j d }g }t| |D ]\}}tt|| }|dd|}||  q|S )a6  Produces Python lists given a batch of sentences with
    their corresponding relative lengths.

    Arguments
    ---------
    batch : torch.Tensor
        Batch of sentences gathered in a batch.
    lengths : torch.Tensor
        Relative length of each sentence in the batch.

    Returns
    -------
    as_list : list
        A python list of the corresponding input tensor.

    Example
    -------
    >>> batch=torch.rand([4,100])
    >>> lengths=torch.tensor([0.5,0.6,0.7,1.0])
    >>> snt_list=undo_padding(batch, lengths)
    >>> len(snt_list)
    4
       r   )shapezipinttorchroundnarrowappendtolist)batchlengthsbatch_max_lenas_listseq
seq_lengthactual_sizeseq_true r   Y/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/speechbrain/utils/data_utils.pyundo_padding   s   
r   c              	   C   s6  d}d}d}d}t | }	t }
|	D ]}t j| |}t j|r-|
t|||||d }
q|durJd}d}|D ]
}||v rA|d }q7|t|krJd}|dur]d}|D ]
}||v r\d} nqR|durxd}|D ]
}||v ro|d }qe|t|krxd}|durd}|D ]
}||v rd} nq|r|r|s|s|
| q|
S )a  Returns a list of files found within a folder.

    Different options can be used to restrict the search to some specific
    patterns.

    Arguments
    ---------
    dirName : str
        The directory to search.
    match_and : list
        A list that contains patterns to match. The file is
        returned if it matches all the entries in `match_and`.
    match_or : list
        A list that contains patterns to match. The file is
        returned if it matches one or more of the entries in `match_or`.
    exclude_and : list
        A list that contains patterns to match. The file is
        returned if it matches none of the entries in `exclude_and`.
    exclude_or : list
        A list that contains pattern to match. The file is
        returned if it fails to match one of the entries in `exclude_or`.

    Returns
    -------
    allFiles : list
        The list of files matching the patterns.

    Example
    -------
    >>> get_all_files('tests/samples/RIRs', match_and=['3.wav'])
    ['tests/samples/RIRs/rir3.wav']
    TF)	match_andmatch_orexclude_and
exclude_orNr   r   )	oslistdirlistpathjoinisdirget_all_fileslenr
   )dirNamer   r   r   r   match_and_entrymatch_or_entryexclude_or_entryexclude_and_entry
listOfFileallFilesentryfullPathmatch_foundeler   r   r   r!   =   st   $



r!   ,Tc                 C   s`   g }t | ddd}tj|||d}|D ]	}|||  qW d   |S 1 s)w   Y  |S )a  Gets a list from the selected field of the input csv file.

    Arguments
    ---------
    csvfile: path
        Path to the csv file.
    field: str
        Field of the csv file used to create the list.
    delimiter: str
        Delimiter of the csv file.
    skipinitialspace: bool
        Set it to true to skip initial spaces in the entries.

    Returns
    -------
    The list of files in the given field of a csv
     zutf-8)newlineencoding)	delimiterskipinitialspaceN)opencsv
DictReaderr
   )csvfilefieldr2   r3   lstcsvfreaderrowr   r   r   get_list_from_csv   s   
r=   c                 C   sZ   t | t| }g }d}|t | k r+|| t|t||   ||7 }|t | k s|S )a  Returns a list of splits in the sequence.

    Arguments
    ---------
    seq : iterable
        The input list, to be split.
    num : int
        The number of chunks to produce.

    Returns
    -------
    A list of lists, length num and containing all elements of seq.

    Example
    -------
    >>> split_list([1, 2, 3, 4, 5, 6, 7, 8, 9], 4)
    [[1, 2], [3, 4], [5, 6], [7, 8, 9]]
    g        )r"   floatr
   r   )r   numavgoutlastr   r   r   
split_list   s   rC   c                 c   s>    |   D ]\}}t|tu rt|E dH  q||fV  qdS )a}  Yield each (key, value) of a nested dictionary.

    Arguments
    ---------
    dictionary : dict
        The nested dictionary to list.

    Yields
    ------
    `(key, value)` tuples from the dictionary.

    Example
    -------
    >>> rec_dict={'lev1': {'lev2': {'lev3': 'current_val'}}}
    >>> [item for item in recursive_items(rec_dict)]
    [('lev3', 'current_val')]
    N)itemstypedictrecursive_items)
dictionarykeyvaluer   r   r   rG      s   rG   Fc                 C   sv   |  D ]4\}}t|tjjr|| v rt| |i | q|r4|| vr4td| ddd |  D  || |< qdS )a  Similar function to `dict.update`, but for a nested `dict`.

    From: https://stackoverflow.com/a/3233356

    If you have to a nested mapping structure, for example:

        {"a": 1, "b": {"c": 2}}

    Say you want to update the above structure with:

        {"b": {"d": 3}}

    This function will produce:

        {"a": 1, "b": {"c": 2, "d": 3}}

    Instead of:

        {"a": 1, "b": {"d": 3}}

    Arguments
    ---------
    d : dict
        Mapping to be updated.
    u : dict
        Mapping to update with.
    must_match : bool
        Whether to throw an error if the key in `u` does not exist in `d`.

    Example
    -------
    >>> d = {'a': 1, 'b': {'c': 2}}
    >>> recursive_update(d, {'b': {'d': 3}})
    >>> d
    {'a': 1, 'b': {'c': 2, 'd': 3}}
    z
Override 'z' not found in: c                 S   s   g | ]}|qS r   r   ).0rI   r   r   r   
<listcomp>-  s    z$recursive_update.<locals>.<listcomp>N)	rD   
isinstancecollectionsabcMappingrecursive_updategetKeyErrorkeys)du
must_matchkvr   r   r   rQ     s   '
rQ   c              	   C   s  zt jj  t jj rG dd dtj}t| j	}|j
ddd d| vr0t| | nGtj|r>tj|rp|rptd|  d|  |ddd	| d
d d}tjj| ||jd W d   n1 sjw   Y  nt| d |r|du rtj|}td| d|  |dr|dst|d'}	t|dd d}
t|	|
 W d   n1 sw   Y  W d   n1 sw   Y  nt|| |rt| W t jj  dS W t jj  dS W t jj  dS W t jj  dS t jj  w )a0  Downloads the file from the given source and saves it in the given
    destination path.

     Arguments
    ---------
    source : path or url
        Path of the source file. If the source is an URL, it downloads it from
        the web.
    dest : path
        Destination path.
    unpack : bool
        If True, it unpacks the data in the dest folder.
        The archive is preserved.

        File formats supported for unpacking/decompression are:

        - any format enumerated by `shutil.get_archive_formats()`, usually
          including `.tar`, `.tar.gz`, `.zip`.
        - plain `.gz` file (when not a `.tar` archive)

        Note that you should ALWAYS trust an archive you are extracting, for
        security reasons.
    dest_unpack: path
        Path where to store the unpacked dataset
    replace_existing : bool
        If True, replaces the existing files.
    write_permissions: bool
        When set to True, all the files in the dest_unpack directory will be granted write permissions.
        This option is active only when unpack=True.
    c                   @   s   e Zd ZdZdddZdS )z*download_file.<locals>.DownloadProgressBarzDownloadProgressBar class.r   Nc                 S   s&   |dur|| _ | || | j  dS )z$Needed to support multigpu training.N)totalupdaten)selfbbsizetsizer   r   r   	update_toa  s   z4download_file.<locals>.DownloadProgressBar.update_to)r   r   N)__name__
__module____qualname____doc__ra   r   r   r   r   DownloadProgressBar^  s    rf   T)parentsexist_okhttpzDownloading z to Br   /)unit
unit_scaleminitersdesc)filename
reporthookNz exists. Skipping downloadzExtracting z.gzz.tar.gzrbwb)sbutilsdistributedddp_barrierif_main_processtqdmpathlibPathresolveparentmkdirshutilcopyfiler   r   isfileprintspliturllibrequesturlretrievera   dirnameendswithgzipr4   copyfileobjunpack_archiveset_writing_permissions)sourcedestunpackdest_unpackreplace_existingwrite_permissionsrf   dest_dirtf_inf_outr   r   r   download_file3  sb   &



4r   c                 C   s>   t | D ]\}}}|D ]}t j||}t |d qqdS )z
    This function sets user writing permissions to all the files in the given folder.

    Arguments
    ---------
    folder_path : folder
        Folder whose files will be granted write permissions.
    i  N)r   walkr   r   chmod)folder_pathrootdirsfiles	file_name	file_pathr   r   r   r     s   	r   constantc                 C   s   t || jks	J g }g }t |d }d}|dkrL|| | j| ks&J d|d|| | j|  g || j| ||   |d8 }|d7 }|dkstjjj| |||d} | |fS )a  
    This function takes a torch tensor of arbitrary shape and pads it to target
    shape by appending values on the right.

    Arguments
    ---------
    tensor : torch.Tensor
        Input tensor whose dimension we need to pad.
    target_shape : (list, tuple)
        Target shape we want for the target tensor its len must be equal to tensor.ndim
    mode : str
        Pad mode, please refer to torch.nn.functional.pad documentation.
    value : float
        Pad value, please refer to torch.nn.functional.pad documentation.

    Returns
    -------
    tensor : torch.Tensor
        Padded tensor.
    valid_vals : list
        List containing proportion for each dimension of original, non-padded values.
    r   r   z4Target shape must be >= original shape for every dimmoderJ   )	r"   ndimr   extendr
   r   nn
functionalpad)tensortarget_shaper   rJ   pads
valid_valsijr   r   r   pad_right_to  s    	r   tensorsc           	         s  t stdt dkrd dtdgfS tfddtdt D s/tdg }td jD ](  dkrRt fdddd	 D sRtd
|	t
 fddD  q8g }g }D ]}t||||d\}}|	| |	|d  qgt|}|t|fS )aG  Given a list of torch tensors it batches them together by padding to the right
    on each dimension in order to get same length for all.

    Arguments
    ---------
    tensors : list
        List of tensor we wish to pad together.
    mode : str
        Padding mode see torch.nn.functional.pad documentation.
    value : float
        Padding value see torch.nn.functional.pad documentation.

    Returns
    -------
    tensor : torch.Tensor
        Padded tensor.
    valid_vals : list
        List containing proportion for each dimension of original, non-padded values.

    zTensors list must not be emptyr   r   g      ?c                    s    g | ]} | j  d  j kqS r   )r   )rK   r   )r   r   r   rL     s     z#batch_pad_right.<locals>.<listcomp>z/All tensors must have same number of dimensionsc                    s$   g | ]}|j   d  j   kqS r   r   rK   xdimr   r   r   rL     s   $ Nz<Tensors should have same dimensions except for the first onec                    s   g | ]}|j   qS r   r   r   r   r   r   rL         r   )r"   
IndexError	unsqueezer   r   allranger   EnvironmentErrorr
   maxr   stack)	r   r   rJ   	max_shapebatchedvalidr   paddedvalid_percentr   r   r   batch_pad_right  s:   


r   c                 C   s   |   S )z,A very basic functional version of str.split)r   )textr   r   r   split_by_whitespace  s   r   c                    s   t | tjr| j i S t | tjjr! fdd|  D S t | tr9t	| dr9t
|  fdd| D  S t | tjjrJ fdd| D S t	| drW| j i S | S )	zMoves data to device, or other type, and handles containers.

    Very similar to torch.utils.data._utils.pin_memory.pin_memory,
    but applies .to() instead.
    c                    s(   i | ]\}}|t |g R i qS r   recursive_to)rK   rX   sampleargskwargsr   r   
<dictcomp>  s    z recursive_to.<locals>.<dictcomp>_fieldsc                 3   s&    | ]}t |g R i V  qd S Nr   rK   r   r   r   r   	<genexpr>   s   $ zrecursive_to.<locals>.<genexpr>c                    s"   g | ]}t |g R i qS r   r   r   r   r   r   rL   #  s   " z recursive_to.<locals>.<listcomp>to)rM   r   Tensorr   rN   rO   rP   rD   tuplehasattrrE   Sequence)datar   r   r   r   r   r     s   
r   z[SaUO]c                 C   sH  | d }t |}t|tjrBd}z&tjj dur.tdd | D }| 	|}|
|}tj| d|dW S  tyA   |  Y S w |jdkr|jdkr|jdkrz.|jd	ks\|jd
krrt|jjdurh| W S tdd | D W S |jdkr}t| W S W dS  ty   |  Y S w t|trtj| tjdS t|trt| S | S )a\  Makes a tensor from list of batch values.

    Note that this doesn't need to zip(*) values together
    as PaddedBatch connects them already (by key).

    Here the idea is not to error out.

    This is modified from:
    https://github.com/pytorch/pytorch/blob/c0deb231db76dbea8a9d326401417f7d1ce96ed5/torch/utils/data/_utils/collate.py#L42
    r   Nc                 S   s   g | ]}|  qS r   )numelr   r   r   r   rL   B      z'mod_default_collate.<locals>.<listcomp>)rA   numpystr_string_ndarraymemmapc                 S   s   g | ]}t |qS r   )r   	as_tensor)rK   r^   r   r   r   rL   U  r   r   )dtype)rE   rM   r   r   rw   r   get_worker_infosumstorage_new_sharednewr   RuntimeErrorrc   rb   np_str_obj_array_patternsearchr   strmod_default_collater   r   r>   r   float64r   )r   elem	elem_typerA   r   r   r   r   r   r   /  sB   









r   c                 C   sH   dd }t | tjjjr | \}}||\}}tjj|||fS || S )a  Splits a path to source and filename

    This also handles URLs and Huggingface hub paths, in addition to
    regular paths.

    Arguments
    ---------
    path : str or FetchSource

    Returns
    -------
    str
        Source
    str
        Filename
    c                 S   s   d| v r| j dddS d| fS )zCore function to split path.rk   r   )maxsplitz./)rsplit)srcr   r   r   r   t  s   zsplit_path.<locals>.split)rM   rv   rw   fetchingFetchSource)r   r   
fetch_from
fetch_pathr   rq   r   r   r   
split_pathb  s   r   c                 C   s*   t | dr
|  }n| }dd | D S )a  Converts a namedtuple or dictionary containing tensors
    to their scalar value

    Arguments
    ---------
    value: dict or namedtuple
        a dictionary or named tuple of tensors

    Returns
    -------
    result: dict
        a result dictionary
    _asdictc                 S   s   i | ]	\}}||  qS r   )item)rK   rI   
item_valuer   r   r   r     s    zscalarize.<locals>.<dictcomp>)r   r   rD   )rJ   
value_dictr   r   r   	scalarize  s   

r   c                 C   s    |  | jd| |     S )ah  Reshape the tensor to be of a shape compatible with the target
    tensor, only valid if x.dim() <= y.dim()

    Arguments
    ---------
    x: torch.Tensor
        the original tensor
    target: torch.Tensor
        the tensor whose shape

    Returns
    -------
    result: torch.Tensor
        a view of tensor x reshaped to a shape compatible with y
    r   )viewr   r   )r   targetr   r   r   unsqueeze_as  s    r      r   c                 C   sj   |  |}|}|| }|dkr||| 7 }t| j}|||< t| ||d\}	}
|dur1|||  }|	|fS )a  Adds extra padding to the specified dimension of a tensor to make
    it divisible  by the specified factor. This is useful when passing
    variable-length sequences to downsampling UNets or other similar
    architectures in which inputs are expected to be divisible by the
    downsampling factor

    Arguments
    ---------
    tensor: torch.Tensor
        the tensor to be padded, of arbitrary dimension

    length: torch.Tensor
        a 1-D tensor of relative lengths

    factor: int
        the divisibility factor

    len_dim: int
        the index of the dimension used as the length

    pad_value: int
        the value with which outputs will be padded

    Returns
    -------
    tensor_padded: torch.Tensor
        the tensor, with additional padding if required
    length: torch.Tensor
        the adjusted length tensor, if provided

    Example
    -------
    >>> x = torch.tensor([[1, 2, 3, 4],
    ...                   [5, 6, 0, 0]])
    >>> lens = torch.tensor([1., .5])
    >>> x_pad, lens_pad = pad_divisible(x, length=lens, factor=5)
    >>> x_pad
    tensor([[1, 2, 3, 4, 0],
            [5, 6, 0, 0, 0]])
    >>> lens_pad
    tensor([0.8000, 0.4000])
    r   )rJ   N)sizer   r   r   )r   lengthfactorlen_dim	pad_valuetime_dimdesired_time_dimgap	new_shapetensor_padded_r   r   r   pad_divisible  s   
+
r  c                 C   s$   t |D ]\}}| |d|} q| S )a   Trims the specified tensor to match the specified shape

    Arguments
    ---------
    tensor: torch.Tensor
        a tensor
    shape: enumerable
        the desired shape

    Returns
    -------
    tensor: torch.Tensor
        the trimmed tensor
    r   )	enumerater	   )r   r   r   r  r   r   r   trim_to_shape  s   r  c                 C   s   t | |jS )a'  Trims the specified tensor to match the shape of another
    tensor (at most)

    Arguments
    ---------
    tensor: torch.Tensor:
        a tensor
    other: torch.Tensor
        the tensor whose shape to match

    Returns
    -------
    tensor: torch.Tensor
        the trimmed tensor
    )r  r   )r   otherr   r   r   trim_as  s   r  c                 C   s"   t | |}||}t||}|S )ad  A swiss-army-knife helper function to match the shape of a tensor to
    match that of another tensor - useful for masks, etc.

    Arguments
    ---------
    tensor: torch.Tensor:
        a tensor
    other: torch.Tensor
        the tensor whose shape to match

    Returns
    -------
    tensor: torch.Tensor
        the tensor with matching shape
    )r   	expand_asr  )r   r  resultr   r   r   match_shape  s   


r  c                    s   t t | }t|}|d||| }t|d}||7 }t|| t }t|	 |f}t
 rC | }|S  fdd|D }|S )ap  Shuffles batches of fixed size within a sequence

    Arguments
    ---------
    items: sequence
        a tensor or an indexable sequence, such as a list
    batch_size: int
        the batch size

    Returns
    -------
    items: sequence
        the original items. If a tensor was passed, a tensor
        will be returned. Otherwise, it will return a list
    rl   r   c                    s   g | ]} | qS r   r   )rK   idxrD   r   r   rL   C  r   z!batch_shuffle.<locals>.<listcomp>)mathfloorr"   r   randpermr   expandarangeconcatflatten	is_tensor)rD   
batch_sizebatch_countbatches	batch_idxbatch_offsettailr  r   r  r   batch_shuffle'  s   

r%  c                    s&  | d }t  fdd| D |j}t dd |D }||d  }t||}t||}t|||dd\}}	t|||dd\}
}|		  
 }t|j}|| < t ||j}t| |
|||	D ]\}}}}}t||| }t||| }|| ||< qg|	dd	d	f  | }||fS )
a  Concatenates multiple padded feature tensors into a single
    padded tensor in a vectorized manner without including the
    padding in the final tensor, adding padding only at the end.
    The function supports optional relative sicing of the tensors.

    One possible use case is to concatenate batches of spectrograms
    or audio.

    Arguments
    ---------
    feats: list
        a list of padded tensors
    lens: list
        a list of length tensors
    dim: int
        The dimension on which to perform concatenation
    feats_slice_start: list
        offsets, relative to the beginning of the sequence, for each
        of the tensors being concatenated. This is useful if only
        a subsequence of some slices is included
    feats_slice_end: list
        offsets, relative to the end of the sequence, for each
        of the tensors being concatenated. This is useful if only
        a subsequence of some slices is included

    Returns
    -------
    out: torch.Tensor
        a concatenated tensor
    r   c                    s   g | ]}|  qS r   )r  rK   r   r   r   r   rL   i  r   z*concat_padded_features.<locals>.<listcomp>c                 S      g | ]}| d qS r   r   )rK   len_relr   r   r   rL   l  r   rl   T)
cumulativeFN)r   r   r   devicer  r   r   _offset_to_tensor_lens_to_boundariesr   r   r   r   zerosr   _boundaries_to_maskr>   )featslensr   feats_slice_startfeats_slice_end
first_itemitem_lengthslens_abs	out_startout_endin_startin_endtotal_length	out_shaperA   r   item_in_startitem_in_enditem_out_startitem_out_endin_maskout_maskout_lensr   r   r   concat_padded_featuresG  s4   !





rD  c                 C   s   | du rd}|S t | r| }|S t| trt ||  }|S t| trEt| d tr9t | d|j	}|S t 
dd | D }|S td)a!  Converts a variety of offset representations to a component x batch tensor,
    used by concat_padded_features. offset can be a tensor, a list of tensors (where
    each element is a tensor of relative offsets similar to lengths), a list of floats
    (in which case all batch elements are presumed to have the same offset)

    Arguments
    ---------
    offset: list|Tensor
        a list or tensor of offsets
    lengths: torch.Tensor
        a length tensor

    Returns
    -------
    result: torch.Tensor
        a tensor of offsets
    Nr   rl   c                 S   r'  r   r(  r&  r   r   r   rL     r   z%_offset_to_tensor.<locals>.<listcomp>z:The offset must be a number, a tensor or a list of tensors)r   r  rM   r   	ones_liker   r   r   r   r+  r  
ValueError)offsetr   r  r   r   r   r,    s$   



r,  c                 C   s   |  d}td|f | j}|du r td| j}n| |   }|du r6td| j}n| |   }|r^| | | }tj||gdd}	|	j	ddddddf }
n
tj| j
 | j}
|
|7 }
|
|  | }|
|fS )a  Converts a tensor of lengths to a tensor of start and end
    boundaries, used for concat_padded_features

    Arguments
    ---------
    lengths: torch.Tensor
        a (component x batch) tensor of absolute lengths
    slice_start: torch.Tensor
        a (component x batch) tensor of relative start offsets
    slice_end: torch.Tensor
        a (component x batch) tensor of relative end offsets
    cumulative: True
        if true, the start of a given component is assumed to
        be at the end of the previous component.
        if false, all components start at the beginning of the
        length dimension

    Returns
    -------
    start: torch.Tensor
        the starting boundary
    end: torch.Tensor
        the ending boundary
    rl   r   Nr   r   )r  r   r.  r   r   r+  r   r  r  cumsumr   )r   slice_start	slice_endr*  r  batch_paddingstart_offset
end_offseteffective_lengthseffective_lengths_zpadstartendr   r   r   r-    s$   
r-  c           	      C   s>   t | |}|  }t||d}t||d}||k||k @ }|S )a;  For a given features tensor and tensors of start and end indexes,
    computes the corresponding Boolean mask

    Arguments
    ---------
    target: torch.Tensor
        the target tensor
    start: torch.Tensor
        the tensor indicating the starting positions along the length
        dimension within each batch
    end: torch.Tensor
        the tensor indicating the final positions within each batch
    len_dim: int
        the dimension used as the length

    Returns
    -------
    mask: torch.Tensor
        a Boolean mask of the same shape as target
    r   )length_ranger   unsqueeze_1d)	r   rP  rQ  r  	out_range	feats_dim
item_startitem_endmaskr   r   r   r/    s   
r/  c                 C   s   dg| }d||< | | S )a  Unsqueezes a 1-D tensor to the specified number of
    dimension preserving one dimension and creating "dummy" dimensions
    elsewhere

    Arguments
    ---------
    value: torch.Tensor
        A 1-D tensor
    dim: int
        the number of dimension
    value_dim: int
        the dimension that the value tensor represents

    Returns
    -------
    result: torch.Tensor
        a dim-dimensional tensor
    N.r   )rJ   r   	value_dimunsqueeze_dimr   r   r   rS     s   
rS  c                 C   sN   |  |}t|| j}t||  |}dd t| j|jD }|j	| S )a  Creates a tensor with a range in a single dimension to one matching the shape
    of a its tensor

    Arguments
    ---------
    feats: torch.Tensor
        a features tensor of arbitrary shape
    len_dim: torch.Tensor
        the dimension used as length

    Returns
    -------
    result: torch.Tensor
        a tensor matching the shape of feats with an 0 to max-length range along
        the length dimension repeated across other dimensions
    c                 S   s   g | ]\}}|| qS r   r   )rK   
feats_sizeout_sizer   r   r   rL   ,  s    z length_range.<locals>.<listcomp>)
r  r   r  r   r+  rS  r   r   r   repeat)r0  r  max_lenfeats_rangerA   
repeat_dimr   r   r   rR    s   

rR  c                 C   s   t td|  S )zReturns all dimensions of the specified tensor
    except the batch dimension

    Arguments
    ---------
    sample: torch.Tensor
        an arbitrary tensor

    Returns
    -------
    dims: list
        a list of dimensions
    r   )r   r   r   )r   r   r   r   non_batch_dims3  s   ra  c                 C   s@   |du rt |  }t| }| | j|d|| j|d S )a#  A metric function that computes the mean of each sample, excluding
    padding

    Arguments
    ---------
    sample: torch.Tensor
        a tensor of spectrograms
    mask: torch.Tensor
        a length mask

    Returns
    -------
    result: torch.Tensor
        a tensor fo means
    Nr   )r   rE  boolra  r   r  r   rX  dimsr   r   r   masked_meanD  s   "re  c                 C   sd   |du rt |  }t| }tt| || }| | | d }|j|d||j|dd   S )a1  A metric function that computes the standard deviation of each
    sample, excluding padding

    Arguments
    ---------
    sample: torch.Tensor
        a tensor of spectrograms
    mask: torch.Tensor
        a length mask

    Returns
    -------
    result: torch.Tensor
        a tensor fo means
    Nr  r   r   )	r   rE  rb  ra  r   re  r   r  sqrt)r   rX  rd  meandiff_sqr   r   r   
masked_stdZ  s    ri  c                 C   s:   |du rt |  }t| }| |  t jj|dS a  A metric function that computes the minimum of each sample

    Arguments
    ---------
    sample: torch.Tensor
        a tensor of spectrograms
    mask: torch.Tensor
        a length mask

    Returns
    -------
    result: torch.Tensor
        a tensor fo means
    Nr   )r   rE  rb  ra  masked_fillinfaminrc  r   r   r   
masked_mint  s   rn  c                 C   s<   |du rt |  }t| }| |  t j j|dS rj  )r   rE  rb  ra  rk  rl  amaxrc  r   r   r   
masked_max  s   rp  c                 C   s&   t | |t| |t| |t| |dS )a  Returns standard distribution statistics (mean, std, min, max)

    Arguments
    ---------
    sample: torch.Tensor
        a tensor of spectrograms
    mask: torch.Tensor
        a length mask

    Returns
    -------
    result: torch.Tensor
        a tensor fo means
    )rg  stdminr   )re  ri  rn  rp  )r   rX  r   r   r   
dist_stats  s
   rs  c                    s    fddt    D S )a  Returns all possible key-value combinations from
    the given dictionary

    Arguments
    ---------
    values: dict
        A dictionary with lists of values as values
        Example:
        {
            "digit": [1,2,3],
            "speaker": [10, 20]
        }

    Returns
    -------
    result: list
        a list of dictionaries in which each dictionary
        is a possible permutations
    c                    s    g | ]}t |t  kr|qS r   )r"   r&  valuesr   r   rL     s
    z+dict_value_combinations.<locals>.<listcomp>)dict_value_combinations_genrT   rt  r   rt  r   dict_value_combinations  s   
rw  c           	      c   s^    |sdS |^}}| | }|D ]}||i}t | |D ]}t|}|| |V  q|V  qdS )a  Returns a generation of permutations of the specified
    values dictionary

    Arguments
    ---------
    values: dict
        A dictionary with lists of values as values
        Example:
        {
            "digit": [1,2,3],
            "speaker": [10, 20]
        }
    keys: list
        the keys to consider

    Returns
    -------
    result: generator
        a generator of dictionaries in which each dictionary
        is a possible permutation
    N)rv  rF   r[   )	ru  rT   rI   rest
key_valuesrJ   currsubr   r   r   r   rv    s   
rv  )NNNN)r.   T)F)FNFF)r   r   )Nr  r   r   )r   NN)NNTr   r   )8re   collections.abcrN   r5   r   r  r   r|   rer   urllib.requestr   numbersr   r   r{   speechbrainrv   r   r!   r=   rC   rG   rQ   r   r   r   r   r   r   r   compiler   r   r   r   r   r  r  r  r  r%  rD  r,  r-  r/  rS  rR  ra  re  ri  rn  rp  rs  rw  rv  r   r   r   r   <module>   sr    
"

o 
5
`
*?
3"
>!
B%

6




