

'''simple docstring'''
import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
    from transformers import WhisperFeatureExtractor

if is_torch_available():
    import torch

_snake_case         =  random.Random()







def  _A		(     snake_case		,							snake_case=1.0		,							snake_case=None		,							snake_case=None					)      ->     int:
   if rng is None:
      _lowercase      :				Dict      					=       global_rng

   _lowercase      :				int      					=       []
   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  ):


   def __init__(			self      ,    _UpperCamelCase      ,    _UpperCamelCase=7      ,    _UpperCamelCase=400      ,    _UpperCamelCase=2000      ,    _UpperCamelCase=10      ,    _UpperCamelCase=160      ,    _UpperCamelCase=8      ,    _UpperCamelCase=0.0      ,    _UpperCamelCase=4000      ,    _UpperCamelCase=False      ,    _UpperCamelCase=True      ,    ):





      """simple docstring"""





      _lowercase      :				List[Any]      					=       parent
      _lowercase      :				Union[str, Any]      					=       batch_size
      _lowercase      :				List[Any]      					=       min_seq_length
      _lowercase      :				int      					=       max_seq_length
      _lowercase      :				int      					=       (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
      _lowercase      :				str      					=       padding_value
      _lowercase      :				List[Any]      					=       sampling_rate
      _lowercase      :				List[str]      					=       return_attention_mask
      _lowercase      :				List[Any]      					=       do_normalize
      _lowercase      :				Any      					=       feature_size
      _lowercase      :				Optional[int]      					=       chunk_length
      _lowercase      :				List[str]      					=       hop_length


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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






   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase=False      ,    _UpperCamelCase=False  ):





      """simple docstring"""





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

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




@require_torch
@require_torchaudio
class        a__  (							lowerCamelCase_  ,				unittest.TestCase  ):
   _SCREAMING_SNAKE_CASE   :					List[str]     	=							WhisperFeatureExtractor if is_speech_available() else None


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       WhisperFeatureExtractionTester(self  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				List[str]      					=       self.feature_extraction_class(**self.feat_extract_dict  )

      with tempfile.TemporaryDirectory() as tmpdirname:
         _lowercase      :				str      					=       feat_extract_first.save_pretrained(_UpperCamelCase  )[0]
         check_json_file_has_correct_format(_UpperCamelCase  )
         _lowercase      :				Union[str, Any]      					=       self.feature_extraction_class.from_pretrained(_UpperCamelCase  )

      _lowercase      :				Tuple      					=       feat_extract_first.to_dict()
      _lowercase      :				int      					=       feat_extract_second.to_dict()
      _lowercase      :				List[str]      					=       feat_extract_first.mel_filters
      _lowercase      :				List[Any]      					=       feat_extract_second.mel_filters
      self.assertTrue(np.allclose(_UpperCamelCase      ,    _UpperCamelCase  )  )
      self.assertEqual(_UpperCamelCase      ,    _UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				List[str]      					=       self.feature_extraction_class(**self.feat_extract_dict  )

      with tempfile.TemporaryDirectory() as tmpdirname:
         _lowercase      :				Tuple      					=       os.path.join(_UpperCamelCase      ,    "feat_extract.json"  )
         feat_extract_first.to_json_file(_UpperCamelCase  )
         _lowercase      :				Dict      					=       self.feature_extraction_class.from_json_file(_UpperCamelCase  )

      _lowercase      :				Any      					=       feat_extract_first.to_dict()
      _lowercase      :				Optional[int]      					=       feat_extract_second.to_dict()
      _lowercase      :				List[Any]      					=       feat_extract_first.mel_filters
      _lowercase      :				Union[str, Any]      					=       feat_extract_second.mel_filters
      self.assertTrue(np.allclose(_UpperCamelCase      ,    _UpperCamelCase  )  )
      self.assertEqual(_UpperCamelCase      ,    _UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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

      # Test feature size
      _lowercase      :				Optional[int]      					=       feature_extractor(_UpperCamelCase      ,    padding="max_length"      ,    return_tensors="np"  ).input_features
      self.assertTrue(input_features.ndim == 3  )
      self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames  )
      self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size  )

      # Test not batched input
      _lowercase      :				str      					=       feature_extractor(speech_inputs[0]      ,    return_tensors="np"  ).input_features
      _lowercase      :				Union[str, Any]      					=       feature_extractor(np_speech_inputs[0]      ,    return_tensors="np"  ).input_features
      self.assertTrue(np.allclose(_UpperCamelCase      ,    _UpperCamelCase      ,    atol=1E-3  )  )

      # Test batched
      _lowercase      :				str      					=       feature_extractor(_UpperCamelCase      ,    return_tensors="np"  ).input_features
      _lowercase      :				List[Any]      					=       feature_extractor(_UpperCamelCase      ,    return_tensors="np"  ).input_features
      for enc_seq_a, enc_seq_a in zip(_UpperCamelCase      ,    _UpperCamelCase  ):
         self.assertTrue(np.allclose(_UpperCamelCase      ,    _UpperCamelCase      ,    atol=1E-3  )  )

      # Test 2-D numpy arrays are batched.
      _lowercase      :				int      					=       [floats_list((1, x)  )[0] for x in (800, 800, 800)]
      _lowercase      :				Dict      					=       np.asarray(_UpperCamelCase  )
      _lowercase      :				List[Any]      					=       feature_extractor(_UpperCamelCase      ,    return_tensors="np"  ).input_features
      _lowercase      :				int      					=       feature_extractor(_UpperCamelCase      ,    return_tensors="np"  ).input_features
      for enc_seq_a, enc_seq_a in zip(_UpperCamelCase      ,    _UpperCamelCase  ):
         self.assertTrue(np.allclose(_UpperCamelCase      ,    _UpperCamelCase      ,    atol=1E-3  )  )

      # Test truncation required
      _lowercase      :				Union[str, Any]      					=       [floats_list((1, x)  )[0] for x in range(200      ,    (feature_extractor.n_samples + 500)      ,    200  )]
      _lowercase      :				int      					=       [np.asarray(_UpperCamelCase  ) for speech_input in speech_inputs]

      _lowercase      :				Optional[Any]      					=       [x[: feature_extractor.n_samples] for x in speech_inputs]
      _lowercase      :				Any      					=       [np.asarray(_UpperCamelCase  ) for speech_input in speech_inputs_truncated]

      _lowercase      :				Any      					=       feature_extractor(_UpperCamelCase      ,    return_tensors="np"  ).input_features
      _lowercase      :				Any      					=       feature_extractor(_UpperCamelCase      ,    return_tensors="np"  ).input_features
      for enc_seq_a, enc_seq_a in zip(_UpperCamelCase      ,    _UpperCamelCase  ):
         self.assertTrue(np.allclose(_UpperCamelCase      ,    _UpperCamelCase      ,    atol=1E-3  )  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      import torch

      _lowercase      :				Any      					=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
      _lowercase      :				Optional[Any]      					=       np.random.rand(100      ,    32  ).astype(np.floataa  )
      _lowercase      :				Tuple      					=       np_speech_inputs.tolist()

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


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Union[str, Any]      					=       load_dataset("hf-internal-testing/librispeech_asr_dummy"      ,    "clean"      ,    split="validation"  )
      # automatic decoding with librispeech
      _lowercase      :				str      					=       ds.sort("id"  ).select(range(_UpperCamelCase  )  )[:num_samples]["audio"]

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


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       torch.tensor(
          [
              0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
              0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
              0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
              -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
          ]  )
      # fmt: on

      _lowercase      :				Union[str, Any]      					=       self._load_datasamples(1  )
      _lowercase      :				Optional[Any]      					=       WhisperFeatureExtractor()
      _lowercase      :				Union[str, Any]      					=       feature_extractor(_UpperCamelCase      ,    return_tensors="pt"  ).input_features
      self.assertEqual(input_features.shape      ,    (1, 80, 3000)  )
      self.assertTrue(torch.allclose(input_features[0, 0, :30]      ,    _UpperCamelCase      ,    atol=1E-4  )  )






   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				str      					=       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
      _lowercase      :				int      					=       self._load_datasamples(1  )[0]
      _lowercase      :				Any      					=       ((audio - audio.min()) / (audio.max() - audio.min())) * 65535  # Rescale to [0, 65535] to show issue
      _lowercase      :				List[str]      					=       feat_extract.zero_mean_unit_var_norm([audio]      ,    attention_mask=_UpperCamelCase  )[0]

      self.assertTrue(np.all(np.mean(_UpperCamelCase  ) < 1E-3  )  )
      self.assertTrue(np.all(np.abs(np.var(_UpperCamelCase  ) - 1  ) < 1E-3  )  )









'''simple docstring'''
from timeit import timeit







def  _A		(     snake_case					)      ->     int:
   if number < 0:
      raise ValueError("the value of input must not be negative"					)
   _lowercase      :				Union[str, Any]      					=       0
   while number:
      number &= number - 1
      result += 1
   return result







def  _A		(     snake_case					)      ->     int:
   if number < 0:
      raise ValueError("the value of input must not be negative"					)
   _lowercase      :				int      					=       0
   while number:
      if number % 2 == 1:
         result += 1
      number >>= 1
   return result







def  _A		(     )      ->     None:

   def do_benchmark(snake_case					) -> None:
      _lowercase      :				Optional[int]      					=       "import __main__ as z"
      print(F'''Benchmark when {number = }:'''					)
      print(F'''{get_set_bits_count_using_modulo_operator(snake_case					) = }'''					)
      _lowercase      :				int      					=       timeit("z.get_set_bits_count_using_modulo_operator(25)"		,							setup=snake_case					)
      print(F'''timeit() runs in {timing} seconds'''					)
      print(F'''{get_set_bits_count_using_brian_kernighans_algorithm(snake_case					) = }'''					)
      _lowercase      :				Optional[int]      					=       timeit(
          "z.get_set_bits_count_using_brian_kernighans_algorithm(25)"		,							setup=snake_case		,							)
      print(F'''timeit() runs in {timing} seconds'''					)

   for number in (25, 37, 58, 0):
      do_benchmark(snake_case					)
      print()


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    benchmark()






