





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

lowercase__				:Union[str, Any]				   =       random.Random()


def       lowerCamelCase_       (   UpperCAmelCase_  ,			UpperCAmelCase_=1.0  ,			UpperCAmelCase_=None  ,			UpperCAmelCase_=None  )						->Any:





  """simple docstring"""


  if rng is None:
    __UpperCAmelCase    :						Optional[int]       =						global_rng

  __UpperCAmelCase    :						Any       =						[]
  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 							snake_case							(			unittest.TestCase ):

      '''simple docstring'''



      def __init__(							self       :      Any						,				__lowercase       :      Any						,				__lowercase       :      Optional[int]=7						,				__lowercase       :      List[str]=400						,				__lowercase       :      str=2_000						,				__lowercase       :      List[str]=10						,				__lowercase       :      Optional[int]=160						,				__lowercase       :      List[str]=8						,				__lowercase       :      Optional[Any]=0.0						,				__lowercase       :      str=4_000						,				__lowercase       :      Union[str, Any]=False						,				__lowercase       :      Optional[Any]=True						,				):


        '''simple docstring'''




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

      def       A_					(							self       :      Any ):


        '''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       A_					(							self       :      Any						,				__lowercase       :      int=False						,				__lowercase       :      Union[str, Any]=False ):


        '''simple docstring'''




        def _flatten(__lowercase       :      str ):
          return list(itertools.chain(*__lowercase ) )

        if equal_length:
          __UpperCAmelCase    :						Union[str, Any]       =						[floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )]
        else:
          # make sure that inputs increase in size
          __UpperCAmelCase    :						Optional[Any]       =						[
              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    :						Optional[int]       =						[np.asarray(__lowercase ) for x in speech_inputs]
        return speech_inputs




@require_torch
@require_torchaudio
class 							snake_case							(			__UpperCAmelCase      ,  unittest.TestCase ):

      '''simple docstring'''



      _A     :       Dict         =       WhisperFeatureExtractor if is_speech_available() else None

      def       A_					(							self       :      Dict ):


        '''simple docstring'''




        __UpperCAmelCase    :						int       =						WhisperFeatureExtractionTester(self )

      def       A_					(							self       :      Any ):


        '''simple docstring'''




        __UpperCAmelCase    :						Union[str, Any]       =						self.feature_extraction_class(**self.feat_extract_dict )

        with tempfile.TemporaryDirectory() as tmpdirname:
          __UpperCAmelCase    :						str       =						feat_extract_first.save_pretrained(__lowercase )[0]
          check_json_file_has_correct_format(__lowercase )
          __UpperCAmelCase    :						List[str]       =						self.feature_extraction_class.from_pretrained(__lowercase )

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

      def       A_					(							self       :      Dict ):


        '''simple docstring'''




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

        with tempfile.TemporaryDirectory() as tmpdirname:
          __UpperCAmelCase    :						Tuple       =						os.path.join(__lowercase						,				'''feat_extract.json''' )
          feat_extract_first.to_json_file(__lowercase )
          __UpperCAmelCase    :						Tuple       =						self.feature_extraction_class.from_json_file(__lowercase )

        __UpperCAmelCase    :						Dict       =						feat_extract_first.to_dict()
        __UpperCAmelCase    :						Optional[Any]       =						feat_extract_second.to_dict()
        __UpperCAmelCase    :						Union[str, Any]       =						feat_extract_first.mel_filters
        __UpperCAmelCase    :						List[str]       =						feat_extract_second.mel_filters
        self.assertTrue(np.allclose(__lowercase						,				__lowercase ) )
        self.assertEqual(__lowercase						,				__lowercase )

      def       A_					(							self       :      Union[str, Any] ):


        '''simple docstring'''




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

        # Test feature size
        __UpperCAmelCase    :						Union[str, Any]       =						feature_extractor(__lowercase						,				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
        __UpperCAmelCase    :						str       =						feature_extractor(speech_inputs[0]						,				return_tensors='''np''' ).input_features
        __UpperCAmelCase    :						str       =						feature_extractor(np_speech_inputs[0]						,				return_tensors='''np''' ).input_features
        self.assertTrue(np.allclose(__lowercase						,				__lowercase						,				atol=1e-3 ) )

        # Test batched
        __UpperCAmelCase    :						Dict       =						feature_extractor(__lowercase						,				return_tensors='''np''' ).input_features
        __UpperCAmelCase    :						List[str]       =						feature_extractor(__lowercase						,				return_tensors='''np''' ).input_features
        for enc_seq_a, enc_seq_a in zip(__lowercase						,				__lowercase ):
          self.assertTrue(np.allclose(__lowercase						,				__lowercase						,				atol=1e-3 ) )

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

        # Test truncation required
        __UpperCAmelCase    :						List[str]       =						[floats_list((1, x) )[0] for x in range(200						,				(feature_extractor.n_samples + 500)						,				200 )]
        __UpperCAmelCase    :						Optional[int]       =						[np.asarray(__lowercase ) for speech_input in speech_inputs]

        __UpperCAmelCase    :						str       =						[x[: feature_extractor.n_samples] for x in speech_inputs]
        __UpperCAmelCase    :						Any       =						[np.asarray(__lowercase ) for speech_input in speech_inputs_truncated]

        __UpperCAmelCase    :						List[Any]       =						feature_extractor(__lowercase						,				return_tensors='''np''' ).input_features
        __UpperCAmelCase    :						List[Any]       =						feature_extractor(__lowercase						,				return_tensors='''np''' ).input_features
        for enc_seq_a, enc_seq_a in zip(__lowercase						,				__lowercase ):
          self.assertTrue(np.allclose(__lowercase						,				__lowercase						,				atol=1e-3 ) )

      def       A_					(							self       :      Optional[int] ):


        '''simple docstring'''




        import torch

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

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

      def       A_					(							self       :      List[Any]						,				__lowercase       :      str ):


        '''simple docstring'''




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

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

      def       A_					(							self       :      List[str] ):


        '''simple docstring'''




        __UpperCAmelCase    :						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

        __UpperCAmelCase    :						List[Any]       =						self._load_datasamples(1 )
        __UpperCAmelCase    :						Union[str, Any]       =						WhisperFeatureExtractor()
        __UpperCAmelCase    :						Optional[int]       =						feature_extractor(__lowercase						,				return_tensors='''pt''' ).input_features
        self.assertEqual(input_features.shape						,				(1, 80, 3_000) )
        self.assertTrue(torch.allclose(input_features[0, 0, :30]						,				__lowercase						,				atol=1e-4 ) )







      def       A_					(							self       :      Optional[Any] ):


        '''simple docstring'''




        __UpperCAmelCase    :						List[str]       =						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
        __UpperCAmelCase    :						Optional[Any]       =						self._load_datasamples(1 )[0]
        __UpperCAmelCase    :						Any       =						((audio - audio.min()) / (audio.max() - audio.min())) * 65_535  # Rescale to [0, 65535] to show issue
        __UpperCAmelCase    :						Tuple       =						feat_extract.zero_mean_unit_var_norm([audio]						,				attention_mask=__lowercase )[0]

        self.assertTrue(np.all(np.mean(__lowercase ) < 1e-3 ) )
        self.assertTrue(np.all(np.abs(np.var(__lowercase ) - 1 ) < 1e-3 ) )






"""simple docstring"""





def       lowerCamelCase_       (   UpperCAmelCase_  )						->float:





  """simple docstring"""


  return 10 - x * x


def       lowerCamelCase_       (   UpperCAmelCase_  ,			UpperCAmelCase_  )						->float:





  """simple docstring"""


  if equation(UpperCAmelCase_  ) * equation(UpperCAmelCase_  ) >= 0:
    raise ValueError('''Wrong space!'''  )

  __UpperCAmelCase    :						Tuple       =						a
  while (b - a) >= 0.01:
    # Find middle point
    __UpperCAmelCase    :						List[str]       =						(a + b) / 2
    # Check if middle point is root
    if equation(UpperCAmelCase_  ) == 0.0:
      break
    # Decide the side to repeat the steps
    if equation(UpperCAmelCase_  ) * equation(UpperCAmelCase_  ) < 0:
      __UpperCAmelCase    :						Union[str, Any]       =						c
    else:
      __UpperCAmelCase    :						str       =						c
  return c


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  print(bisection(-2, 5))
  print(bisection(0, 6))