



'''simple docstring'''





import itertools
import random
import unittest

import numpy as np

from transformers import is_speech_available
from transformers.testing_utils import require_torch, require_torchaudio

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
  from transformers import SpeechaTextFeatureExtractor

lowercase_		       =  random.Random()




def lowerCAmelCase  (__A  ,	__A=1.0  ,	__A=None  ,	__A=None):



     """simple docstring"""



     if rng is None:
          _a      =  global_rng

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

     return values






@require_torch
@require_torchaudio
class __A			(  unittest.TestCase						):



 '''simple docstring'''







 def __init__(self ,   A ,   A=7 ,   A=400 ,   A=2_000 ,   A=24 ,   A=24 ,   A=0.0 ,   A=16_000 ,   A=True ,   A=True ,   )    ->     Optional[Any]:


      """simple docstring"""



      _a      =  parent
      _a      =  batch_size
      _a      =  min_seq_length
      _a      =  max_seq_length
      _a      =  (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
      _a      =  feature_size
      _a      =  num_mel_bins
      _a      =  padding_value
      _a      =  sampling_rate
      _a      =  return_attention_mask
      _a      =  do_normalize



 def 					a__  (self       )    ->     str:


      """simple docstring"""



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



 def 					a__  (self ,   A=False ,   A=False       )    ->     List[str]:


      """simple docstring"""



      def _flatten(A       ):
           return list(itertools.chain(*A       )       )

      if equal_length:
           _a      =  [floats_list((self.max_seq_length, self.feature_size)       ) for _ in range(self.batch_size       )]
      else:
           # make sure that inputs increase in size
           _a      =  [
               floats_list((x, self.feature_size)       )
               for x in range(self.min_seq_length ,   self.max_seq_length ,   self.seq_length_diff       )
           ]
      if numpify:
           _a      =  [np.asarray(A       ) for x in speech_inputs]
      return speech_inputs






@require_torch
@require_torchaudio
class __A			(  A   ,   unittest.TestCase						):



 '''simple docstring'''







 __lowerCamelCase    :       Tuple          =       SpeechaTextFeatureExtractor if is_speech_available() else None



 def 					a__  (self       )    ->     Tuple:


      """simple docstring"""



      _a      =  SpeechaTextFeatureExtractionTester(self       )



 def 					a__  (self ,   A       )    ->     Any:


      """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 					a__  (self       )    ->     List[str]:


      """simple docstring"""



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

      # Test feature size
      _a      =  feature_extractor(A ,   padding=A ,   return_tensors='''np'''       ).input_features
      self.assertTrue(input_features.ndim == 3       )
      self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size       )

      # Test not batched input
      _a      =  feature_extractor(speech_inputs[0] ,   return_tensors='''np'''       ).input_features
      _a      =  feature_extractor(np_speech_inputs[0] ,   return_tensors='''np'''       ).input_features
      self.assertTrue(np.allclose(A ,   A ,   atol=1E-3       )       )

      # Test batched
      _a      =  feature_extractor(A ,   return_tensors='''np'''       ).input_features
      _a      =  feature_extractor(A ,   return_tensors='''np'''       ).input_features
      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.
      _a      =  [floats_list((1, x)       )[0] for x in (800, 800, 800)]
      _a      =  np.asarray(A       )
      _a      =  feature_extractor(A ,   return_tensors='''np'''       ).input_features
      _a      =  feature_extractor(A ,   return_tensors='''np'''       ).input_features
      for enc_seq_a, enc_seq_a in zip(A ,   A       ):
           self.assertTrue(np.allclose(A ,   A ,   atol=1E-3       )       )



 def 					a__  (self       )    ->     List[str]:


      """simple docstring"""



      _a      =  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
      _a      =  [floats_list((1, x)       )[0] for x in range(800 ,   1_400 ,   200       )]

      _a      =  ['''longest''', '''max_length''', '''do_not_pad''']
      _a      =  [None, 16, None]
      for max_length, padding in zip(A ,   A       ):
           _a      =  feature_extractor(
               A ,   padding=A ,   max_length=A ,   return_attention_mask=A       )
           _a      =  inputs.input_features
           _a      =  inputs.attention_mask
           _a      =  [np.sum(A       ) for x in attention_mask]

           self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]       )
           self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]       )
           self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]       )



 def 					a__  (self       )    ->     Optional[int]:


      """simple docstring"""



      _a      =  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
      _a      =  [floats_list((1, x)       )[0] for x in range(800 ,   1_400 ,   200       )]

      _a      =  ['''longest''', '''max_length''', '''do_not_pad''']
      _a      =  [None, 16, None]
      for max_length, padding in zip(A ,   A       ):
           _a      =  feature_extractor(
               A ,   max_length=A ,   padding=A ,   return_tensors='''np''' ,   return_attention_mask=A       )
           _a      =  inputs.input_features
           _a      =  inputs.attention_mask
           _a      =  [np.sum(A       ) for x in attention_mask]

           self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]]       )
           self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1E-6       )
           self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]]       )
           self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1E-6       )
           self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]]       )



 def 					a__  (self       )    ->     Tuple:


      """simple docstring"""



      _a      =  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
      _a      =  [floats_list((1, x)       )[0] for x in range(800 ,   1_400 ,   200       )]
      _a      =  feature_extractor(
          A ,   padding='''max_length''' ,   max_length=4 ,   truncation=A ,   return_tensors='''np''' ,   return_attention_mask=A ,   )
      _a      =  inputs.input_features
      _a      =  inputs.attention_mask
      _a      =  np.sum(attention_mask == 1 ,   axis=1       )

      self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]       )
      self._check_zero_mean_unit_variance(input_features[1]       )
      self._check_zero_mean_unit_variance(input_features[2]       )



 def 					a__  (self       )    ->     str:


      """simple docstring"""



      _a      =  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
      _a      =  [floats_list((1, x)       )[0] for x in range(800 ,   1_400 ,   200       )]
      _a      =  feature_extractor(
          A ,   padding='''longest''' ,   max_length=4 ,   truncation=A ,   return_tensors='''np''' ,   return_attention_mask=A ,   )
      _a      =  inputs.input_features
      _a      =  inputs.attention_mask
      _a      =  np.sum(attention_mask == 1 ,   axis=1       )

      self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]       )
      self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]       )
      self._check_zero_mean_unit_variance(input_features[2]       )

      # make sure that if max_length < longest -> then pad to max_length
      self.assertEqual(input_features.shape ,   (3, 4, 24)       )

      _a      =  [floats_list((1, x)       )[0] for x in range(800 ,   1_400 ,   200       )]
      _a      =  feature_extractor(
          A ,   padding='''longest''' ,   max_length=16 ,   truncation=A ,   return_tensors='''np''' ,   return_attention_mask=A ,   )
      _a      =  inputs.input_features
      _a      =  inputs.attention_mask
      _a      =  np.sum(attention_mask == 1 ,   axis=1       )

      self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]]       )
      self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]]       )
      self._check_zero_mean_unit_variance(input_features[2]       )

      # make sure that if max_length < longest -> then pad to max_length
      self.assertEqual(input_features.shape ,   (3, 6, 24)       )



 def 					a__  (self       )    ->     Tuple:


      """simple docstring"""



      import torch

      _a      =  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
      _a      =  np.random.rand(100 ,   32       ).astype(np.floataa       )
      _a      =  np_speech_inputs.tolist()

      for inputs in [py_speech_inputs, np_speech_inputs]:
           _a      =  feature_extractor.pad([{'''input_features''': inputs}] ,   return_tensors='''np'''       )
           self.assertTrue(np_processed.input_features.dtype == np.floataa       )
           _a      =  feature_extractor.pad([{'''input_features''': inputs}] ,   return_tensors='''pt'''       )
           self.assertTrue(pt_processed.input_features.dtype == torch.floataa       )



 def 					a__  (self ,   A       )    ->     Dict:


      """simple docstring"""



      from datasets import load_dataset

      _a      =  load_dataset('''hf-internal-testing/librispeech_asr_dummy''' ,   '''clean''' ,   split='''validation'''       )
      # automatic decoding with librispeech
      _a      =  ds.sort('''id'''       ).select(range(A       )       )[:num_samples]['''audio''']

      return [x["array"] for x in speech_samples]



 def 					a__  (self       )    ->     Union[str, Any]:


      """simple docstring"""



      _a      =  np.array([
          -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241,
          -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128,
          -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625,
      ]       )
      # fmt: on

      _a      =  self._load_datasamples(1       )
      _a      =  self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
      _a      =  feature_extractor(A ,   return_tensors='''pt'''       ).input_features
      self.assertEquals(input_features.shape ,   (1, 584, 24)       )
      self.assertTrue(np.allclose(input_features[0, 0, :30] ,   A ,   atol=1E-4       )       )








'''simple docstring'''





from math import sqrt




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and (
         number >= 0
     ), "'number' must been an int and positive"

     _a      =  True

     # 0 and 1 are none primes.
     if number <= 1:
          _a      =  False

     for divisor in range(2  ,	int(round(sqrt(__A))) + 1):
          # if 'number' divisible by 'divisor' then sets 'status'
          # of false and break up the loop.
          if number % divisor == 0:
               _a      =  False
               break

    # precondition
     assert isinstance(__A  ,	__A), "'status' must been from type bool"

     return status




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and (n > 2), "'N' must been an int and > 2"

     # beginList: contains all natural numbers from 2 up to N
     _a      =  list(range(2  ,	n + 1))

     _a      =  []  # this list will be returns.

     # actual sieve of erathostenes
     for i in range(len(__A)):
          for j in range(i + 1  ,	len(__A)):
               if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
                    _a      =  0

    # filters actual prime numbers.
     _a      =  [x for x in begin_list if x != 0]

     # precondition
     assert isinstance(__A  ,	__A), "'ans' must been from type list"

     return ans




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and (n > 2), "'N' must been an int and > 2"

     _a      =  []

     # iterates over all numbers between 2 up to N+1
     # if a number is prime then appends to list 'ans'
     for number in range(2  ,	n + 1):
          if is_prime(__A):
               ans.append(__A)

    # precondition
     assert isinstance(__A  ,	__A), "'ans' must been from type list"

     return ans




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and number >= 0, "'number' must been an int and >= 0"

     _a      =  []  # this list will be returns of the function.

     # potential prime number factors.

     _a      =  2

     _a      =  number

     if number == 0 or number == 1:
          ans.append(__A)

     # if 'number' not prime then builds the prime factorization of 'number'
     elif not is_prime(__A):
          while quotient != 1:
               if is_prime(__A) and (quotient % factor == 0):
                    ans.append(__A)
                    quotient /= factor
               else:
                    factor += 1

     else:
          ans.append(__A)

     # precondition
     assert isinstance(__A  ,	__A), "'ans' must been from type list"

     return ans




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and (
         number >= 0
     ), "'number' bust been an int and >= 0"

     _a      =  0

     # prime factorization of 'number'
     _a      =  prime_factorization(__A)

     _a      =  max(__A)

     # precondition
     assert isinstance(__A  ,	__A), "'ans' must been from type int"

     return ans




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and (
         number >= 0
     ), "'number' bust been an int and >= 0"

     _a      =  0

     # prime factorization of 'number'
     _a      =  prime_factorization(__A)

     _a      =  min(__A)

     # precondition
     assert isinstance(__A  ,	__A), "'ans' must been from type int"

     return ans




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A), "'number' must been an int"
     assert isinstance(number % 2 == 0  ,	__A), "compare bust been from type bool"

     return number % 2 == 0




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A), "'number' must been an int"
     assert isinstance(number % 2 != 0  ,	__A), "compare bust been from type bool"

     return number % 2 != 0




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert (
         isinstance(__A  ,	__A) and (number > 2) and is_even(__A)
     ), "'number' must been an int, even and > 2"

     _a      =  []  # this list will returned

     # creates a list of prime numbers between 2 up to 'number'
     _a      =  get_prime_numbers(__A)
     _a      =  len(__A)

     # run variable for while-loops.
     _a      =  0
     _a      =  None

     # exit variable. for break up the loops
     _a      =  True

     while i < len_pn and loop:
          _a      =  i + 1

          while j < len_pn and loop:
               if prime_numbers[i] + prime_numbers[j] == number:
                    _a      =  False
                    ans.append(prime_numbers[i])
                    ans.append(prime_numbers[j])

               j += 1

          i += 1

     # precondition
     assert (
         isinstance(__A  ,	__A)
         and (len(__A) == 2)
         and (ans[0] + ans[1] == number)
         and is_prime(ans[0])
         and is_prime(ans[1])
     ), "'ans' must contains two primes. And sum of elements must been eq 'number'"

     return ans




def lowerCAmelCase  (__A  ,	__A):



     """simple docstring"""



     assert (
         isinstance(__A  ,	__A)
         and isinstance(__A  ,	__A)
         and (numbera >= 0)
         and (numbera >= 0)
     ), "'number1' and 'number2' must been positive integer."

     _a      =  0

     while numbera != 0:
          _a      =  numbera % numbera
          _a      =  numbera
          _a      =  rest

     # precondition
     assert isinstance(__A  ,	__A) and (
         numbera >= 0
     ), "'number' must been from type int and positive"

     return numbera




def lowerCAmelCase  (__A  ,	__A):



     """simple docstring"""



     assert (
         isinstance(__A  ,	__A)
         and isinstance(__A  ,	__A)
         and (numbera >= 1)
         and (numbera >= 1)
     ), "'number1' and 'number2' must been positive integer."

     _a      =  1  # actual answer that will be return.

     # for kgV (x,1)
     if numbera > 1 and numbera > 1:
          # builds the prime factorization of 'number1' and 'number2'
          _a      =  prime_factorization(__A)
          _a      =  prime_factorization(__A)

     elif numbera == 1 or numbera == 1:
          _a      =  []
          _a      =  []
          _a      =  max(__A  ,	__A)

     _a      =  0
     _a      =  0

     _a      =  []  # captured numbers int both 'primeFac1' and 'primeFac2'

     # iterates through primeFac1
     for n in prime_fac_a:
          if n not in done:
               if n in prime_fac_a:
                    _a      =  prime_fac_a.count(__A)
                    _a      =  prime_fac_a.count(__A)

                    for _ in range(max(__A  ,	__A)):
                         ans *= n

               else:
                    _a      =  prime_fac_a.count(__A)

                    for _ in range(__A):
                         ans *= n

               done.append(__A)

    # iterates through primeFac2
     for n in prime_fac_a:
          if n not in done:
               _a      =  prime_fac_a.count(__A)

               for _ in range(__A):
                    ans *= n

               done.append(__A)

    # precondition
     assert isinstance(__A  ,	__A) and (
         ans >= 0
     ), "'ans' must been from type int and positive"

     return ans




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and (n >= 0), "'number' must been a positive int"

     _a      =  0
     _a      =  2  # this variable holds the answer

     while index < n:
          index += 1

          ans += 1  # counts to the next number

          # if ans not prime then
          # runs to the next prime number.
          while not is_prime(__A):
               ans += 1

    # precondition
     assert isinstance(__A  ,	__A) and is_prime(
         __A), "'ans' must been a prime number and from type int"

     return ans




def lowerCAmelCase  (__A  ,	__A):



     """simple docstring"""



     assert (
         is_prime(__A) and is_prime(__A) and (p_number_a < p_number_a)
     ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"

     _a      =  p_number_a + 1  # jump to the next number

     _a      =  []  # this list will be returns.

     # if number is not prime then
     # fetch the next prime number.
     while not is_prime(__A):
          number += 1

     while number < p_number_a:
          ans.append(__A)

          number += 1

          # fetch the next prime number.
          while not is_prime(__A):
               number += 1

    # precondition
     assert (
         isinstance(__A  ,	__A)
         and ans[0] != p_number_a
         and ans[len(__A) - 1] != p_number_a
     ), "'ans' must been a list without the arguments"

     # 'ans' contains not 'pNumber1' and 'pNumber2' !
     return ans




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and (n >= 1), "'n' must been int and >= 1"

     _a      =  []  # will be returned.

     for divisor in range(1  ,	n + 1):
          if n % divisor == 0:
               ans.append(__A)

    # precondition
     assert ans[0] == 1 and ans[len(__A) - 1] == n, "Error in function getDivisiors(...)"

     return ans




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and (
         number > 1
     ), "'number' must been an int and >= 1"

     _a      =  get_divisors(__A)

     # precondition
     assert (
         isinstance(__A  ,	__A)
         and (divisors[0] == 1)
         and (divisors[len(__A) - 1] == number)
     ), "Error in help-function getDivisiors(...)"

     # summed all divisors up to 'number' (exclusive), hence [:-1]
     return sum(divisors[:-1]) == number




def lowerCAmelCase  (__A  ,	__A):



     """simple docstring"""



     assert (
         isinstance(__A  ,	__A)
         and isinstance(__A  ,	__A)
         and (denominator != 0)
     ), "The arguments must been from type int and 'denominator' != 0"

     # build the greatest common divisor of numerator and denominator.
     _a      =  gcd(abs(__A)  ,	abs(__A))

     # precondition
     assert (
         isinstance(__A  ,	__A)
         and (numerator % gcd_of_fraction == 0)
         and (denominator % gcd_of_fraction == 0)
     ), "Error in function gcd(...,...)"

     return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and (n >= 0), "'n' must been a int and >= 0"

     _a      =  1  # this will be return.

     for factor in range(1  ,	n + 1):
          ans *= factor

     return ans




def lowerCAmelCase  (__A):



     """simple docstring"""



     assert isinstance(__A  ,	__A) and (n >= 0), "'n' must been an int and >= 0"

     _a      =  0
     _a      =  1
     _a      =  1  # this will be return

     for _ in range(n - 1):
          _a      =  ans
          ans += fiba
          _a      =  tmp

     return ans



