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

lowerCAmelCase			:							List[str]     =random.Random()







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







    '''simple docstring'''
    if rng is None:
        _lowerCamelCase     :		str 						=						global_rng

    _lowerCamelCase     :		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 	__snake_case	( unittest.TestCase		):





      '''simple docstring'''






      def __init__(					self     :				Tuple    ,  _UpperCamelCase     :				Optional[int]    ,  _UpperCamelCase     :				str=7    ,  _UpperCamelCase     :				Dict=400    ,  _UpperCamelCase     :				str=2000    ,  _UpperCamelCase     :				str=10    ,  _UpperCamelCase     :				Any=160    ,  _UpperCamelCase     :				List[Any]=8    ,  _UpperCamelCase     :				List[str]=0.0    ,  _UpperCamelCase     :				List[Any]=4000    ,  _UpperCamelCase     :				Optional[Any]=False    ,  _UpperCamelCase     :				Dict=True    ,  )				->List[Any]:


          """simple docstring"""


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



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


          """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 	_SCREAMING_SNAKE_CASE    (					self     :				Dict    ,  _UpperCamelCase     :				Dict=False    ,  _UpperCamelCase     :				int=False)				->Union[str, Any]:


          """simple docstring"""


          def _flatten(_UpperCamelCase     :				Optional[Any]):
              return list(itertools.chain(*_UpperCamelCase))

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





@require_torch
@require_torchaudio
class 	__snake_case	( __lowerCAmelCase ,  unittest.TestCase		):





      '''simple docstring'''






      _snake_case    		=       WhisperFeatureExtractor if is_speech_available() else None



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Dict)				->List[str]:


          """simple docstring"""


          _lowerCamelCase     :		int 						=						WhisperFeatureExtractionTester(self)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				int)				->Optional[Any]:


          """simple docstring"""


          _lowerCamelCase     :		int 						=						self.feature_extraction_class(**self.feat_extract_dict)

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

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



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Any)				->List[str]:


          """simple docstring"""


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

          with tempfile.TemporaryDirectory() as tmpdirname:
              _lowerCamelCase     :		Optional[Any] 						=						os.path.join(_UpperCamelCase    ,  """feat_extract.json""")
              feat_extract_first.to_json_file(_UpperCamelCase)
              _lowerCamelCase     :		List[str] 						=						self.feature_extraction_class.from_json_file(_UpperCamelCase)

          _lowerCamelCase     :		Optional[Any] 						=						feat_extract_first.to_dict()
          _lowerCamelCase     :		Dict 						=						feat_extract_second.to_dict()
          _lowerCamelCase     :		List[Any] 						=						feat_extract_first.mel_filters
          _lowerCamelCase     :		Optional[Any] 						=						feat_extract_second.mel_filters
          self.assertTrue(np.allclose(_UpperCamelCase    ,  _UpperCamelCase))
          self.assertEqual(_UpperCamelCase    ,  _UpperCamelCase)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Tuple)				->Tuple:


          """simple docstring"""


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

          # Test feature size
          _lowerCamelCase     :		Tuple 						=						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
          _lowerCamelCase     :		Tuple 						=						feature_extractor(speech_inputs[0]    ,  return_tensors="""np""").input_features
          _lowerCamelCase     :		List[Any] 						=						feature_extractor(np_speech_inputs[0]    ,  return_tensors="""np""").input_features
          self.assertTrue(np.allclose(_UpperCamelCase    ,  _UpperCamelCase    ,  atol=1E-3))

          # Test batched
          _lowerCamelCase     :		Dict 						=						feature_extractor(_UpperCamelCase    ,  return_tensors="""np""").input_features
          _lowerCamelCase     :		Optional[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.
          _lowerCamelCase     :		Any 						=						[floats_list((1, x))[0] for x in (800, 800, 800)]
          _lowerCamelCase     :		Tuple 						=						np.asarray(_UpperCamelCase)
          _lowerCamelCase     :		List[str] 						=						feature_extractor(_UpperCamelCase    ,  return_tensors="""np""").input_features
          _lowerCamelCase     :		List[str] 						=						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
          _lowerCamelCase     :		Union[str, Any] 						=						[floats_list((1, x))[0] for x in range(200    ,  (feature_extractor.n_samples + 500)    ,  200)]
          _lowerCamelCase     :		Optional[int] 						=						[np.asarray(_UpperCamelCase) for speech_input in speech_inputs]

          _lowerCamelCase     :		List[str] 						=						[x[: feature_extractor.n_samples] for x in speech_inputs]
          _lowerCamelCase     :		int 						=						[np.asarray(_UpperCamelCase) for speech_input in speech_inputs_truncated]

          _lowerCamelCase     :		Tuple 						=						feature_extractor(_UpperCamelCase    ,  return_tensors="""np""").input_features
          _lowerCamelCase     :		Dict 						=						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 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[Any])				->Tuple:


          """simple docstring"""


          import torch

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

          for inputs in [py_speech_inputs, np_speech_inputs]:
              _lowerCamelCase     :		List[str] 						=						feature_extractor.pad([{"""input_features""": inputs}]    ,  return_tensors="""np""")
              self.assertTrue(np_processed.input_features.dtype == np.floataa)
              _lowerCamelCase     :		Optional[int] 						=						feature_extractor.pad([{"""input_features""": inputs}]    ,  return_tensors="""pt""")
              self.assertTrue(pt_processed.input_features.dtype == torch.floataa)



      def 	_SCREAMING_SNAKE_CASE    (					self     :				Dict    ,  _UpperCamelCase     :				List[Any])				->Union[str, Any]:


          """simple docstring"""


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

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



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


          """simple docstring"""


          _lowerCamelCase     :		Optional[int] 						=						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

          _lowerCamelCase     :		Union[str, Any] 						=						self._load_datasamples(1)
          _lowerCamelCase     :		Dict 						=						WhisperFeatureExtractor()
          _lowerCamelCase     :		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 	_SCREAMING_SNAKE_CASE    (					self     :				Tuple)				->Union[str, Any]:


          """simple docstring"""


          _lowerCamelCase     :		Union[str, Any] 						=						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
          _lowerCamelCase     :		List[str] 						=						self._load_datasamples(1)[0]
          _lowerCamelCase     :		Optional[Any] 						=						((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535  # Rescale to [0, 65535] to show issue
          _lowerCamelCase     :		Optional[int] 						=						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))





def 						A__  (					__A   , __A	):







    '''simple docstring'''
    _enforce_args(__A   , __A	)
    if n == 0:
        return 0
    _lowerCamelCase     :		Tuple 						=						float("""-inf"""	)
    for i in range(1   , n + 1	):
        _lowerCamelCase     :		Any 						=						max(
            __A   , prices[i - 1] + naive_cut_rod_recursive(n - i   , __A	)	)

    return max_revue







def 						A__  (					__A   , __A	):







    '''simple docstring'''
    _enforce_args(__A   , __A	)
    _lowerCamelCase     :		Optional[Any] 						=						[float("""-inf"""	) for _ in range(n + 1	)]
    return _top_down_cut_rod_recursive(__A   , __A   , __A	)







def 						A__  (					__A   , __A   , __A	):







    '''simple docstring'''
    if max_rev[n] >= 0:
        return max_rev[n]
    elif n == 0:
        return 0
    else:
        _lowerCamelCase     :		int 						=						float("""-inf"""	)
        for i in range(1   , n + 1	):
            _lowerCamelCase     :		Optional[Any] 						=						max(
                __A   , prices[i - 1] + _top_down_cut_rod_recursive(n - i   , __A   , __A	)   , )

        _lowerCamelCase     :		Optional[Any] 						=						max_revenue

    return max_rev[n]







def 						A__  (					__A   , __A	):







    '''simple docstring'''
    _enforce_args(__A   , __A	)

    # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of
    # length 0.
    _lowerCamelCase     :		List[Any] 						=						[float("""-inf"""	) for _ in range(n + 1	)]
    _lowerCamelCase     :		Any 						=						0

    for i in range(1   , n + 1	):
        _lowerCamelCase     :		Any 						=						max_rev[i]
        for j in range(1   , i + 1	):
            _lowerCamelCase     :		List[Any] 						=						max(__A   , prices[j - 1] + max_rev[i - j]	)

        _lowerCamelCase     :		int 						=						max_revenue_i

    return max_rev[n]







def 						A__  (					__A   , __A	):







    '''simple docstring'''
    if n < 0:
        _lowerCamelCase     :		Any 						=						F"""n must be greater than or equal to 0. Got n = {n}"""
        raise ValueError(__A	)

    if n > len(__A	):
        _lowerCamelCase     :		List[Any] 						=						(
            """Each integral piece of rod must have a corresponding price. """
            F"""Got n = {n} but length of prices = {len(__A	)}"""
        )
        raise ValueError(__A	)







def 						A__  (					):







    '''simple docstring'''
    _lowerCamelCase     :		str 						=						[6, 10, 12, 15, 20, 23]
    _lowerCamelCase     :		List[str] 						=						len(__A	)

    # the best revenue comes from cutting the rod into 6 pieces, each
    # of length 1 resulting in a revenue of 6 * 6 = 36.
    _lowerCamelCase     :		Tuple 						=						36

    _lowerCamelCase     :		Any 						=						top_down_cut_rod(__A   , __A	)
    _lowerCamelCase     :		Dict 						=						bottom_up_cut_rod(__A   , __A	)
    _lowerCamelCase     :		List[str] 						=						naive_cut_rod_recursive(__A   , __A	)

    assert expected_max_revenue == max_rev_top_down
    assert max_rev_top_down == max_rev_bottom_up
    assert max_rev_bottom_up == max_rev_naive


if __name__ == "__main__":
    main()




