



'''simple docstring'''





import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowercase_									=    random.Random()

if is_torch_available():
  import torch




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






class __A     (    unittest.TestCase		):



 '''simple docstring'''







 def __init__(self					,  A					,  A=7					,  A=400					,  A=2_000					,  A=1					,  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           =    padding_value
      _a           =    sampling_rate
      _a           =    return_attention_mask
      _a           =    do_normalize



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


      """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    a__    (self					,  A=False					,  A=False			)       ->	Optional[Any]:


      """simple docstring"""



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

      if equal_length:
           _a           =    floats_list((self.batch_size, self.max_seq_length)			)
      else:
           # make sure that inputs increase in size
           _a           =    [
               _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:
           _a           =    [np.asarray(A			) for x in speech_inputs]

      return speech_inputs






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



 '''simple docstring'''







 __lowerCamelCase       :			int		=			ASTFeatureExtractor



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


      """simple docstring"""



      _a           =    ASTFeatureExtractionTester(self			)



 def    a__    (self			)       ->	Dict:


      """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 not batched input
      _a           =    feat_extract(speech_inputs[0]					,  return_tensors='''np'''			).input_values
      _a           =    feat_extract(np_speech_inputs[0]					,  return_tensors='''np'''			).input_values
      self.assertTrue(np.allclose(A					,  A					,  atol=1E-3			)			)

      # Test batched
      _a           =    feat_extract(A					,  padding=A					,  return_tensors='''np'''			).input_values
      _a           =    feat_extract(A					,  padding=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.
      _a           =    [floats_list((1, x)			)[0] for x in (800, 800, 800)]
      _a           =    np.asarray(A			)
      _a           =    feat_extract(A					,  return_tensors='''np'''			).input_values
      _a           =    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			)			)



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


      """simple docstring"""



      import torch

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

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



 def    a__    (self					,  A			)       ->	Optional[Any]:


      """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]



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


      """simple docstring"""



      _a           =    torch.tensor(
          [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776,
           -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133,
           -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936,
           -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869]			)
      # fmt: on

      _a           =    self._load_datasamples(1			)
      _a           =    ASTFeatureExtractor()
      _a           =    feature_extractor(A					,  return_tensors='''pt'''			).input_values
      self.assertEquals(input_values.shape					,  (1, 1_024, 128)			)
      self.assertTrue(torch.allclose(input_values[0, 0, :30]					,  A					,  atol=1E-4			)			)








'''simple docstring'''





def lowerCAmelCase    (__A):



     """simple docstring"""



     if not isinstance(__A    ,      __A):
          raise ValueError('''multiplicative_persistence() only accepts integral values''')
     if num < 0:
          raise ValueError('''multiplicative_persistence() does not accept negative values''')

     _a           =    0
     _a           =    str(__A)

     while len(__A) != 1:
          _a           =    [int(__A) for i in num_string]

          _a           =    1
          for i in range(0    ,      len(__A)):
               total *= numbers[i]

          _a           =    str(__A)

          steps += 1
     return steps




def lowerCAmelCase    (__A):



     """simple docstring"""



     if not isinstance(__A    ,      __A):
          raise ValueError('''additive_persistence() only accepts integral values''')
     if num < 0:
          raise ValueError('''additive_persistence() does not accept negative values''')

     _a           =    0
     _a           =    str(__A)

     while len(__A) != 1:
          _a           =    [int(__A) for i in num_string]

          _a           =    0
          for i in range(0    ,      len(__A)):
               total += numbers[i]

          _a           =    str(__A)

          steps += 1
     return steps


if __name__ == "__main__":
  import doctest

  doctest.testmod()



