U
    ,-eG                     @   sr   d Z ddlmZmZmZmZ ddlZddlm	Z	m
Z
 ddlmZmZmZmZmZmZ eeZG dd de
ZdS )	z[
 Sequence feature extraction class for common feature extractors to preprocess sequences.
    )DictListOptionalUnionN   )BatchFeatureFeatureExtractionMixin)PaddingStrategy
TensorTypeis_tf_tensoris_torch_tensorloggingto_numpyc                       s  e Zd ZdZeeed fddZdeee	e e
eef e
ee	e f e	e
eef  f eeeef ee eee ee eeeef  edd	d
Zdejddfee
eejf ef ee eee ee edddZdee
eejf ef ee ee ee dddZdddZ  ZS )SequenceFeatureExtractora  
    This is a general feature extraction class for speech recognition.

    Args:
        feature_size (`int`):
            The feature dimension of the extracted features.
        sampling_rate (`int`):
            The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
        padding_value (`float`):
            The value that is used to fill the padding values / vectors.
    )feature_sizesampling_ratepadding_valuec                    s@   || _ || _|| _|dd| _|dd| _t jf | d S )Npadding_siderightreturn_attention_maskT)r   r   r   popr   r   super__init__)selfr   r   r   kwargs	__class__ o/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/transformers/feature_extraction_sequence_utils.pyr   *   s    z!SequenceFeatureExtractor.__init__TNF)processed_featurespadding
max_length
truncationpad_to_multiple_ofr   return_tensorsreturnc                    s  t ttfr:t d ttfr:fddd  D jd krjtdjd  dt  jd  }|dk	r|nj}t	|dkr|rg d< S |d }	t |	ttfrd}
t	||
 dkr|
d7 }
q|
t	|k r||
 d }	|dkrTt
|	rd	}nHt|	rd
}n8t |	tttttjfr:d}ntd|	 dt|	 d D ]>\}}t |d ttfrt||< ndd |D |< q\j||d}jd  }t	| t fdd D stdg }t D ]8fdd D }j||||d}|| q|tjkrRtfdd|D }tj}i }t D ]rj| ||||d}| D ]J\}}||krg ||< |jttjkr| tj!}|| | qq^t||dS )a  
        Pad input values / input vectors or a batch of input values / input vectors up to predefined length or to the
        max sequence length in the batch.

        Padding side (left/right) padding values are defined at the feature extractor level (with `self.padding_side`,
        `self.padding_value`)

        <Tip>

        If the `processed_features` passed are dictionary of numpy arrays, PyTorch tensors or TensorFlow tensors, the
        result will use the same type unless you provide a different tensor type with `return_tensors`. In the case of
        PyTorch tensors, you will lose the specific device of your tensors however.

        </Tip>

        Args:
            processed_features ([`BatchFeature`], list of [`BatchFeature`], `Dict[str, List[float]]`, `Dict[str, List[List[float]]` or `List[Dict[str, List[float]]]`):
                Processed inputs. Can represent one input ([`BatchFeature`] or `Dict[str, List[float]]`) or a batch of
                input values / vectors (list of [`BatchFeature`], *Dict[str, List[List[float]]]* or *List[Dict[str,
                List[float]]]*) so you can use this method during preprocessing as well as in a PyTorch Dataloader
                collate function.

                Instead of `List[float]` you can have tensors (numpy arrays, PyTorch tensors or TensorFlow tensors),
                see the note above for the return type.
            padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
                Select a strategy to pad the returned sequences (according to the model's padding side and padding
                index) among:

                - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
                  sequence if provided).
                - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
                  acceptable input length for the model if that argument is not provided.
                - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
                  lengths).
            max_length (`int`, *optional*):
                Maximum length of the returned list and optionally padding length (see above).
            truncation (`bool`):
                Activates truncation to cut input sequences longer than `max_length` to `max_length`.
            pad_to_multiple_of (`int`, *optional*):
                If set will pad the sequence to a multiple of the provided value.

                This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
                `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
            return_attention_mask (`bool`, *optional*):
                Whether to return the attention mask. If left to the default, will return the attention mask according
                to the specific feature_extractor's default.

                [What are attention masks?](../glossary#attention-mask)
            return_tensors (`str` or [`~utils.TensorType`], *optional*):
                If set, will return tensors instead of list of python integers. Acceptable values are:

                - `'tf'`: Return TensorFlow `tf.constant` objects.
                - `'pt'`: Return PyTorch `torch.Tensor` objects.
                - `'np'`: Return Numpy `np.ndarray` objects.
        r   c                    s    i | ]   fd dD qS )c                    s   g | ]}|  qS r   r   ).0Zexamplekeyr   r   
<listcomp>   s     z;SequenceFeatureExtractor.pad.<locals>.<dictcomp>.<listcomp>r   )r&   )r   r'   r   
<dictcomp>~   s     z0SequenceFeatureExtractor.pad.<locals>.<dictcomp>zYou should supply an instance of `transformers.BatchFeature` or list of `transformers.BatchFeature` to this method that includes z, but you provided Nattention_maskr   tfptnpztype of z
 unknown: zA. Should be one of a python, numpy, pytorch or tensorflow object.c                 S   s   g | ]}t |qS r   )r   r&   vr   r   r   r)      s     z0SequenceFeatureExtractor.pad.<locals>.<listcomp>)r    r!   c                 3   s   | ]}t | kV  qd S )N)lenr/   )
batch_sizer   r   	<genexpr>   s     z/SequenceFeatureExtractor.pad.<locals>.<genexpr>zLSome items in the output dictionary have a different batch size than others.c                    s   i | ]\}}||  qS r   r   )r&   kr0   )ir   r   r*      s      )r!   r#   r"   c                 3   s    | ]}t | jd   V  qdS )r   N)r1   model_input_names)r&   Zinput_slice)r   r   r   r3      s     )r!   padding_strategyr#   r   )Ztensor_type)"
isinstancelisttupledictr   keysr6   
ValueErrorr   r1   r   r   intfloatr.   ndarraytypeitemsr   _get_padding_strategiesallvaluesrange	_truncateappendr	   LONGESTmax
MAX_LENGTH_paddtypeZfloat64ZastypeZfloat32)r   r   r    r!   r"   r#   r   r$   required_inputZfirst_elementindexr(   valuer7   Ztruncated_inputsinputsZinputs_sliceZbatch_outputsoutputsr   )r2   r5   r   r   r   pad4   s    I 






zSequenceFeatureExtractor.pad)r   r!   r7   r#   r   r%   c           
      C   s|  || j d  }|tjkr t|}|dk	rL|dk	rL|| dkrL|| d | }|tjko`t||k }|rd|krtjt|tjd|d< |rx|t| }| jdkr|rt	|d d|f|d< | j
dkrd|fdfnd|f}	tj	||	d| jd	|| j d < n|| jd
krf|r&t	|d |df|d< | j
dkr>|dfdfn|df}	tj	||	d| jd	|| j d < ntdt| j |S )a  
        Pad inputs (on left/right and up to predefined length or max length in the batch)

        Args:
            processed_features (`Union[Dict[str, np.ndarray], BatchFeature]`):
                Dictionary of input values (`np.ndarray[float]`) / input vectors (`List[np.ndarray[float]]`) or batch
                of inputs values (`List[np.ndarray[int]]`) / input vectors (`List[np.ndarray[int]]`)
            max_length (`int`, *optional*):
                Maximum length of the returned list and optionally padding length (see below)
            padding_strategy (`PaddingStrategy`, *optional*, default to `PaddingStrategy.DO_NOT_PAD`):
                PaddingStrategy to use for padding.

                - PaddingStrategy.LONGEST Pad to the longest sequence in the batch
                - PaddingStrategy.MAX_LENGTH: Pad to the max length (default)
                - PaddingStrategy.DO_NOT_PAD: Do not pad
                The feature_extractor padding sides are defined in self.padding_side:

                    - 'left': pads on the left of the sequences
                    - 'right': pads on the right of the sequences
            pad_to_multiple_of (`int`, *optional*):
                Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to
                enable the use of Tensor Core on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs
                which benefit from having sequence lengths be a multiple of 128.
            return_attention_mask (`bool`, *optional*):
                Set to False to avoid returning attention mask (default: set to model specifics)
        r   Nr   r+   )rM   r   )r   r   Zconstant)Zconstant_valuesleftzInvalid padding strategy:)r6   r	   rI   r1   
DO_NOT_PADr.   ZonesZint32r   rS   r   r   r=   str)
r   r   r!   r7   r#   r   rN   Zneeds_to_be_padded
differenceZpadding_shaper   r   r   rL      sL    "

         zSequenceFeatureExtractor._pad)r   r!   r#   r"   c                 C   s   |s|S |r|dkrt d|| jd  }|dk	rV|dk	rV|| dkrV|| d | }t||k}|r|| jd  d| || jd < d|kr|d d| |d< |S )a  
        Truncate inputs to predefined length or max length in the batch

        Args:
            processed_features(`Union[Dict[str, np.ndarray], BatchFeature]`):
                Dictionary of input values (`np.ndarray[float]`) / input vectors (`List[np.ndarray[float]]`) or batch
                of inputs values (`List[np.ndarray[int]]`) / input vectors (`List[np.ndarray[int]]`)
            max_length (`int`, *optional*):
                maximum length of the returned list and optionally padding length (see below)
            pad_to_multiple_of (`int`, *optional*) :
                Integer if set will pad the sequence to a multiple of the provided value. This is especially useful to
                enable the use of Tensor Core on NVIDIA hardware with compute capability `>= 7.5` (Volta), or on TPUs
                which benefit from having sequence lengths be a multiple of 128.
            truncation (`bool`, *optional*):
                Activates truncation to cut input sequences longer than `max_length` to `max_length`.
        NzKWhen setting ``truncation=True``, make sure that ``max_length`` is defined.r   r   r+   )r=   r6   r1   )r   r   r!   r#   r"   rN   Zneeds_to_be_truncatedr   r   r   rG   *  s     z"SequenceFeatureExtractor._truncatec                 C   s   |dk	r<|dkrt j}qBt|t s,t |}qBt|t rB|}nt j}|dkrf|t jkrftdt j d|t jkr| jdkrtd|S )z3
        Find the correct padding strategy
        FTNzWhen setting ``padding=z(``, make sure that max_length is definedzAsking to pad but the feature_extractor does not have a padding value. Please select a value to use as `padding_value`. For example: `feature_extractor.padding_value = 0.0`.)r	   rI   r8   rU   rK   r=   r   )r   r    r!   r7   r   r   r   rC   U  s$    



z0SequenceFeatureExtractor._get_padding_strategies)TNFNNN)NNN)FN)__name__
__module____qualname____doc__r>   r?   r   r   r   r   r   rV   boolr	   r   r
   rS   rU   r.   r@   r;   rL   rG   rC   __classcell__r   r   r   r   r      s`         
 2K   +r   )r[   typingr   r   r   r   numpyr.   Zfeature_extraction_utilsr   r   utilsr	   r
   r   r   r   r   Z
get_loggerrX   loggerr   r   r   r   r   <module>   s    
