





"""simple docstring"""




import itertools
import random
import unittest

import numpy as np

from transformers import WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST, WavaVecaConfig, WavaVecaFeatureExtractor
from transformers.testing_utils import require_torch, slow

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


__lowerCamelCase	:					List[Any]			  =					random.Random()



def 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase=1.0							,       _lowerCAmelCase=None							,       _lowerCAmelCase=None					)						->			Tuple:







 if rng is None:
  UpperCamelCase     : str	     =       global_rng

 UpperCamelCase     : Dict	     =       []
 for batch_idx in range(shape[0]					):
  values.append([]					)
  for _ in range(shape[1]					):
   values[-1].append(rng.random() * scale					)

 return values



class  A__       (	unittest.TestCase      ):





      def __init__(			self	,							A_	,							A_=7	,							A_=400	,							A_=2000	,							A_=1	,							A_=0.0	,							A_=1_6000	,							A_=True	,							A_=True	,							):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       parent
       UpperCamelCase     : List[Any]	     =       batch_size
       UpperCamelCase     : Optional[int]	     =       min_seq_length
       UpperCamelCase     : Tuple	     =       max_seq_length
       UpperCamelCase     : Tuple	     =       (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
       UpperCamelCase     : Any	     =       feature_size
       UpperCamelCase     : Optional[int]	     =       padding_value
       UpperCamelCase     : Optional[int]	     =       sampling_rate
       UpperCamelCase     : Optional[int]	     =       return_attention_mask
       UpperCamelCase     : int	     =       do_normalize





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       return {
           "feature_size": self.feature_size,
           "padding_value": self.padding_value,
           "sampling_rate": self.sampling_rate,
           "return_attention_mask": self.return_attention_mask,
           "do_normalize": self.do_normalize,
       }





      def 	__UpperCamelCase(			self	,							A_=False	,							A_=False       ):
       '''simple docstring'''




       def _flatten(A_       ):
        return list(itertools.chain(*_a       )       )

       if equal_length:
        UpperCamelCase     : Dict	     =       floats_list((self.batch_size, self.max_seq_length)       )
       else:
        # make sure that inputs increase in size
        UpperCamelCase     : Optional[int]	     =       [
            _flatten(floats_list((x, self.feature_size)       )       )
            for x in range(self.min_seq_length	,							self.max_seq_length	,							self.seq_length_diff       )
        ]

       if numpify:
        UpperCamelCase     : Union[str, Any]	     =       [np.asarray(_a       ) for x in speech_inputs]

       return speech_inputs



class  A__       (	__snake_case	,       unittest.TestCase      ):
      _UpperCAmelCase     :str						   =       WavaVecaFeatureExtractor





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[int]	     =       WavaVecaFeatureExtractionTester(self       )





      def 	__UpperCamelCase(			self	,							A_       ):
       '''simple docstring'''




       self.assertTrue(np.all(np.mean(_a	,							axis=0       ) < 1e-3       )       )
       self.assertTrue(np.all(np.abs(np.var(_a	,							axis=0       ) - 1       ) < 1e-3       )       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
       # create three inputs of length 800, 1000, and 1200
       UpperCamelCase     : Optional[Any]	     =       [floats_list((1, x)       )[0] for x in range(800	,							1400	,							200       )]
       UpperCamelCase     : Any	     =       [np.asarray(_a       ) for speech_input in speech_inputs]

       # Test not batched input
       UpperCamelCase     : Tuple	     =       feat_extract(speech_inputs[0]	,							return_tensors="np"       ).input_values
       UpperCamelCase     : Optional[int]	     =       feat_extract(np_speech_inputs[0]	,							return_tensors="np"       ).input_values
       self.assertTrue(np.allclose(_a	,							_a	,							atol=1e-3       )       )

       # Test batched
       UpperCamelCase     : Tuple	     =       feat_extract(_a	,							return_tensors="np"       ).input_values
       UpperCamelCase     : Union[str, Any]	     =       feat_extract(_a	,							return_tensors="np"       ).input_values
       for enc_seq_a, enc_seq_a in zip(_a	,							_a       ):
        self.assertTrue(np.allclose(_a	,							_a	,							atol=1e-3       )       )

       # Test 2-D numpy arrays are batched.
       UpperCamelCase     : Union[str, Any]	     =       [floats_list((1, x)       )[0] for x in (800, 800, 800)]
       UpperCamelCase     : int	     =       np.asarray(_a       )
       UpperCamelCase     : Union[str, Any]	     =       feat_extract(_a	,							return_tensors="np"       ).input_values
       UpperCamelCase     : List[str]	     =       feat_extract(_a	,							return_tensors="np"       ).input_values
       for enc_seq_a, enc_seq_a in zip(_a	,							_a       ):
        self.assertTrue(np.allclose(_a	,							_a	,							atol=1e-3       )       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : List[Any]	     =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
       UpperCamelCase     : Optional[int]	     =       [floats_list((1, x)       )[0] for x in range(800	,							1400	,							200       )]

       UpperCamelCase     : Dict	     =       ["longest", "max_length", "do_not_pad"]
       UpperCamelCase     : int	     =       [None, 1600, None]
       for max_length, padding in zip(_a	,							_a       ):
        UpperCamelCase     : Any	     =       feat_extract(_a	,							padding=_a	,							max_length=_a	,							return_tensors="np"       )
        UpperCamelCase     : Tuple	     =       processed.input_values

        self._check_zero_mean_unit_variance(input_values[0][:800]       )
        self.assertTrue(input_values[0][800:].sum() < 1e-6       )
        self._check_zero_mean_unit_variance(input_values[1][:1000]       )
        self.assertTrue(input_values[0][1000:].sum() < 1e-6       )
        self._check_zero_mean_unit_variance(input_values[2][:1200]       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
       UpperCamelCase     : Tuple	     =       range(800	,							1400	,							200       )
       UpperCamelCase     : List[str]	     =       [floats_list((1, x)       )[0] for x in lengths]

       UpperCamelCase     : Tuple	     =       ["longest", "max_length", "do_not_pad"]
       UpperCamelCase     : Union[str, Any]	     =       [None, 1600, None]

       for max_length, padding in zip(_a	,							_a       ):
        UpperCamelCase     : List[str]	     =       feat_extract(_a	,							max_length=_a	,							padding=_a       )
        UpperCamelCase     : int	     =       processed.input_values

        self._check_zero_mean_unit_variance(input_values[0][:800]       )
        self._check_zero_mean_unit_variance(input_values[1][:1000]       )
        self._check_zero_mean_unit_variance(input_values[2][:1200]       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
       UpperCamelCase     : Optional[int]	     =       [floats_list((1, x)       )[0] for x in range(800	,							1400	,							200       )]
       UpperCamelCase     : List[Any]	     =       feat_extract(
           _a	,							truncation=_a	,							max_length=1000	,							padding="max_length"	,							return_tensors="np"       )
       UpperCamelCase     : Any	     =       processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]       )
       self._check_zero_mean_unit_variance(input_values[1]       )
       self._check_zero_mean_unit_variance(input_values[2]       )





      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[int]	     =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
       UpperCamelCase     : List[str]	     =       [floats_list((1, x)       )[0] for x in range(800	,							1400	,							200       )]
       UpperCamelCase     : List[Any]	     =       feat_extract(
           _a	,							truncation=_a	,							max_length=1000	,							padding="longest"	,							return_tensors="np"       )
       UpperCamelCase     : List[Any]	     =       processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]       )
       self._check_zero_mean_unit_variance(input_values[1, :1000]       )
       self._check_zero_mean_unit_variance(input_values[2]       )

       # make sure that if max_length < longest -> then pad to max_length
       self.assertTrue(input_values.shape == (3, 1000)       )

       UpperCamelCase     : List[str]	     =       [floats_list((1, x)       )[0] for x in range(800	,							1400	,							200       )]
       UpperCamelCase     : Union[str, Any]	     =       feat_extract(
           _a	,							truncation=_a	,							max_length=2000	,							padding="longest"	,							return_tensors="np"       )
       UpperCamelCase     : Union[str, Any]	     =       processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]       )
       self._check_zero_mean_unit_variance(input_values[1, :1000]       )
       self._check_zero_mean_unit_variance(input_values[2]       )

       # make sure that if max_length > longest -> then pad to longest
       self.assertTrue(input_values.shape == (3, 1200)       )





      @require_torch
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       import torch

       UpperCamelCase     : Any	     =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
       UpperCamelCase     : Tuple	     =       np.random.rand(100       ).astype(np.floataa       )
       UpperCamelCase     : Any	     =       np_speech_inputs.tolist()

       for inputs in [py_speech_inputs, np_speech_inputs]:
        UpperCamelCase     : Any	     =       feature_extractor.pad([{"input_values": inputs}]	,							return_tensors="np"       )
        self.assertTrue(np_processed.input_values.dtype == np.floataa       )
        UpperCamelCase     : List[Any]	     =       feature_extractor.pad([{"input_values": inputs}]	,							return_tensors="pt"       )
        self.assertTrue(pt_processed.input_values.dtype == torch.floataa       )





      @slow
      @require_torch
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       for model_id in WAV_2_VEC_2_PRETRAINED_MODEL_ARCHIVE_LIST:
        UpperCamelCase     : str	     =       WavaVecaConfig.from_pretrained(_a       )
        UpperCamelCase     : Optional[Any]	     =       WavaVecaFeatureExtractor.from_pretrained(_a       )

        # only "layer" feature extraction norm should make use of
        # attention_mask
        self.assertEqual(feat_extract.return_attention_mask	,							config.feat_extract_norm == "layer"       )







import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


__lowerCamelCase	:					List[str]			  =					logging.get_logger(__name__)


__lowerCamelCase	:					Any			  =					r"""
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
            or scores for each vocabulary token after SoftMax.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional stopping criteria specific kwargs.

    Return:
        `bool`. `False` indicates we should continue, `True` indicates we should stop.

"""



class  A__       (	__snake_case      ):





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       raise NotImplementedError("StoppingCriteria needs to be subclassed"       )



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_ = None       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       max_length
       UpperCamelCase     : Dict	     =       max_position_embeddings





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       input_ids.shape[-1]
       UpperCamelCase     : str	     =       cur_len >= self.max_length
       if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
        logger.warning_once(
            "This is a friendly reminder - the current text generation call will exceed the model's predefined "
            F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """
            "exceptions, performance degradation, or nothing at all."       )
       return is_done



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_       ):
       '''simple docstring'''




       warnings.warn(
           "The class `MaxNewTokensCriteria` is deprecated. "
           F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """
           "with `max_length = start_length + max_new_tokens` instead."	,							A_	,							)
       UpperCamelCase     : Union[str, Any]	     =       start_length
       UpperCamelCase     : List[str]	     =       max_new_tokens
       UpperCamelCase     : Tuple	     =       start_length + max_new_tokens





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return input_ids.shape[-1] >= self.max_length



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_ = None       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[int]	     =       max_time
       UpperCamelCase     : Dict	     =       time.time() if initial_timestamp is None else initial_timestamp





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return time.time() - self.initial_timestamp > self.max_time



class  A__       (	__snake_case      ):





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return any(criteria(A_	,							A_       ) for criteria in self       )





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       for stopping_criterium in self:
        if isinstance(A_	,							A_       ):
         return stopping_criterium.max_length
        elif isinstance(A_	,							A_       ):
         return stopping_criterium.max_length
       return None



def 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase					)						->			StoppingCriteriaList:
 UpperCamelCase     : Tuple	     =       stopping_criteria.max_length
 UpperCamelCase     : Union[str, Any]	     =       deepcopy(_lowerCAmelCase					)
 if stopping_max_length is not None and stopping_max_length != max_length:
  warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter"							,       _lowerCAmelCase					)
 elif stopping_max_length is None:
  new_stopping_criteria.append(MaxLengthCriteria(max_length=_lowerCAmelCase					)					)
 return new_stopping_criteria
