




import itertools
import random
import unittest

import numpy as np

from transformers import BatchFeature, SpeechTaFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
     import torch


__a          =			random.Random()







def lowerCamelCase__       (      _lowercase			,						_lowercase=1.0			,						_lowercase=None			,						_lowercase=None				):

     '''simple docstring'''


     if rng is None:
          UpperCAmelCase_      :							List[str]       =      global_rng

     UpperCAmelCase_      :							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
class   __a(					unittest.TestCase       ):






    """simple docstring"""





    def __init__(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE=7       ,_SCREAMING_SNAKE_CASE=400       ,_SCREAMING_SNAKE_CASE=2_000       ,_SCREAMING_SNAKE_CASE=1       ,_SCREAMING_SNAKE_CASE=0.0       ,_SCREAMING_SNAKE_CASE=16_000       ,_SCREAMING_SNAKE_CASE=True       ,_SCREAMING_SNAKE_CASE=80       ,_SCREAMING_SNAKE_CASE=16       ,_SCREAMING_SNAKE_CASE=64       ,_SCREAMING_SNAKE_CASE="hann_window"       ,_SCREAMING_SNAKE_CASE=80       ,_SCREAMING_SNAKE_CASE=7_600       ,_SCREAMING_SNAKE_CASE=1e-10       ,_SCREAMING_SNAKE_CASE=True       ,)			->		Dict:
         UpperCAmelCase_      :							int       =      parent
         UpperCAmelCase_      :							Any       =      batch_size
         UpperCAmelCase_      :							str       =      min_seq_length
         UpperCAmelCase_      :							List[Any]       =      max_seq_length
         UpperCAmelCase_      :							str       =      (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
         UpperCAmelCase_      :							Any       =      feature_size
         UpperCAmelCase_      :							int       =      padding_value
         UpperCAmelCase_      :							Tuple       =      sampling_rate
         UpperCAmelCase_      :							List[Any]       =      do_normalize
         UpperCAmelCase_      :							int       =      num_mel_bins
         UpperCAmelCase_      :							List[str]       =      hop_length
         UpperCAmelCase_      :							Any       =      win_length
         UpperCAmelCase_      :							Optional[Any]       =      win_function
         UpperCAmelCase_      :							Any       =      fmin
         UpperCAmelCase_      :							List[str]       =      fmax
         UpperCAmelCase_      :							Union[str, Any]       =      mel_floor
         UpperCAmelCase_      :							List[str]       =      return_attention_mask





    def 							a__				(				self  )			->		Optional[int]:
         return {
             "feature_size": self.feature_size,
             "padding_value": self.padding_value,
             "sampling_rate": self.sampling_rate,
             "do_normalize": self.do_normalize,
             "num_mel_bins": self.num_mel_bins,
             "hop_length": self.hop_length,
             "win_length": self.win_length,
             "win_function": self.win_function,
             "fmin": self.fmin,
             "fmax": self.fmax,
             "mel_floor": self.mel_floor,
             "return_attention_mask": self.return_attention_mask,
         }





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE=False       ,_SCREAMING_SNAKE_CASE=False  )			->		Optional[Any]:
         def _flatten(_SCREAMING_SNAKE_CASE  ):
              return list(itertools.chain(*_SCREAMING_SNAKE_CASE  )  )

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

         return speech_inputs





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE=False       ,_SCREAMING_SNAKE_CASE=False  )			->		str:
         if equal_length:
              UpperCAmelCase_      :							List[Any]       =      [floats_list((self.max_seq_length, self.num_mel_bins)  ) for _ in range(self.batch_size  )]
         else:
              # make sure that inputs increase in size
              UpperCAmelCase_      :							List[Any]       =      [
                  floats_list((x, self.num_mel_bins)  )
                  for x in range(self.min_seq_length       ,self.max_seq_length       ,self.seq_length_diff  )
              ]

         if numpify:
              UpperCAmelCase_      :							Union[str, Any]       =      [np.asarray(_SCREAMING_SNAKE_CASE  ) for x in speech_inputs]

         return speech_inputs


@require_torch
class   __a(					_a    ,						unittest.TestCase       ):






    """simple docstring"""





    lowerCAmelCase        =				SpeechTaFeatureExtractor





    def 							a__				(				self  )			->		int:
         UpperCAmelCase_      :							Dict       =      SpeechTaFeatureExtractionTester(self  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE  )			->		Any:
         self.assertTrue(np.all(np.mean(_SCREAMING_SNAKE_CASE       ,axis=0  ) < 1e-3  )  )
         self.assertTrue(np.all(np.abs(np.var(_SCREAMING_SNAKE_CASE       ,axis=0  ) - 1  ) < 1e-3  )  )





    def 							a__				(				self  )			->		Tuple:
         # Tests that all call wrap to encode_plus and batch_encode_plus
         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_      :							Union[str, Any]       =      [np.asarray(_SCREAMING_SNAKE_CASE  ) for speech_input in speech_inputs]

         # Test not batched input
         UpperCAmelCase_      :							List[str]       =      feat_extract(speech_inputs[0]       ,return_tensors='''np'''  ).input_values
         UpperCAmelCase_      :							Union[str, Any]       =      feat_extract(np_speech_inputs[0]       ,return_tensors='''np'''  ).input_values
         self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,atol=1e-3  )  )

         # Test batched
         UpperCAmelCase_      :							int       =      feat_extract(_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  ).input_values
         UpperCAmelCase_      :							Union[str, Any]       =      feat_extract(_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  ).input_values
         for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ):
              self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,atol=1e-3  )  )





    def 							a__				(				self  )			->		Optional[Any]:
         UpperCAmelCase_      :							Union[str, Any]       =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
         UpperCAmelCase_      :							str       =      [floats_list((1, x)  )[0] for x in range(800       ,1_400       ,200  )]

         UpperCAmelCase_      :							Any       =      ['''longest''', '''max_length''', '''do_not_pad''']
         UpperCAmelCase_      :							int       =      [None, 1_600, None]
         for max_length, padding in zip(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ):
              UpperCAmelCase_      :							List[str]       =      feat_extract(_SCREAMING_SNAKE_CASE       ,padding=_SCREAMING_SNAKE_CASE       ,max_length=_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  )
              UpperCAmelCase_      :							Optional[Any]       =      processed.input_values

              self._check_zero_mean_unit_variance(input_values[0][:800]  )
              self.assertTrue(input_values[0][800:].sum() < 1e-6  )
              self._check_zero_mean_unit_variance(input_values[1][:1_000]  )
              self.assertTrue(input_values[0][1_000:].sum() < 1e-6  )
              self._check_zero_mean_unit_variance(input_values[2][:1_200]  )





    def 							a__				(				self  )			->		str:
         UpperCAmelCase_      :							Tuple       =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
         UpperCAmelCase_      :							List[str]       =      range(800       ,1_400       ,200  )
         UpperCAmelCase_      :							int       =      [floats_list((1, x)  )[0] for x in lengths]

         UpperCAmelCase_      :							List[Any]       =      ['''longest''', '''max_length''', '''do_not_pad''']
         UpperCAmelCase_      :							List[str]       =      [None, 1_600, None]

         for max_length, padding in zip(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ):
              UpperCAmelCase_      :							Tuple       =      feat_extract(_SCREAMING_SNAKE_CASE       ,max_length=_SCREAMING_SNAKE_CASE       ,padding=_SCREAMING_SNAKE_CASE  )
              UpperCAmelCase_      :							Optional[int]       =      processed.input_values

              self._check_zero_mean_unit_variance(input_values[0][:800]  )
              self._check_zero_mean_unit_variance(input_values[1][:1_000]  )
              self._check_zero_mean_unit_variance(input_values[2][:1_200]  )





    def 							a__				(				self  )			->		int:
         UpperCAmelCase_      :							Dict       =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
         UpperCAmelCase_      :							str       =      [floats_list((1, x)  )[0] for x in range(800       ,1_400       ,200  )]
         UpperCAmelCase_      :							Optional[int]       =      feat_extract(
             _SCREAMING_SNAKE_CASE       ,truncation=_SCREAMING_SNAKE_CASE       ,max_length=1_000       ,padding='''max_length'''       ,return_tensors='''np'''  )
         UpperCAmelCase_      :							Any       =      processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :800]  )
         self._check_zero_mean_unit_variance(input_values[1]  )
         self._check_zero_mean_unit_variance(input_values[2]  )





    def 							a__				(				self  )			->		Dict:
         UpperCAmelCase_      :							Tuple       =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
         UpperCAmelCase_      :							int       =      [floats_list((1, x)  )[0] for x in range(800       ,1_400       ,200  )]
         UpperCAmelCase_      :							int       =      feat_extract(
             _SCREAMING_SNAKE_CASE       ,truncation=_SCREAMING_SNAKE_CASE       ,max_length=1_000       ,padding='''longest'''       ,return_tensors='''np'''  )
         UpperCAmelCase_      :							str       =      processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :800]  )
         self._check_zero_mean_unit_variance(input_values[1, :1_000]  )
         self._check_zero_mean_unit_variance(input_values[2]  )

         # make sure that if max_length < longest -> then pad to max_length
         self.assertTrue(input_values.shape == (3, 1_000)  )

         UpperCAmelCase_      :							Optional[Any]       =      [floats_list((1, x)  )[0] for x in range(800       ,1_400       ,200  )]
         UpperCAmelCase_      :							Optional[Any]       =      feat_extract(
             _SCREAMING_SNAKE_CASE       ,truncation=_SCREAMING_SNAKE_CASE       ,max_length=2_000       ,padding='''longest'''       ,return_tensors='''np'''  )
         UpperCAmelCase_      :							int       =      processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :800]  )
         self._check_zero_mean_unit_variance(input_values[1, :1_000]  )
         self._check_zero_mean_unit_variance(input_values[2]  )

         # make sure that if max_length > longest -> then pad to longest
         self.assertTrue(input_values.shape == (3, 1_200)  )





    def 							a__				(				self  )			->		Optional[int]:
         UpperCAmelCase_      :							Union[str, Any]       =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
         UpperCAmelCase_      :							Optional[int]       =      np.random.rand(100  ).astype(np.floataa  )
         UpperCAmelCase_      :							Dict       =      np_speech_inputs.tolist()

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





    def 							a__				(				self  )			->		List[str]:
         # Tests that all call wrap to encode_plus and batch_encode_plus
         UpperCAmelCase_      :							List[str]       =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()  )
         # create three inputs of length 800, 1000, and 1200
         UpperCAmelCase_      :							Optional[Any]       =      [floats_list((1, x)  )[0] for x in range(800       ,1_400       ,200  )]
         UpperCAmelCase_      :							List[Any]       =      [np.asarray(_SCREAMING_SNAKE_CASE  ) for speech_input in speech_inputs]

         # Test feature size
         UpperCAmelCase_      :							int       =      feature_extractor(audio_target=_SCREAMING_SNAKE_CASE       ,padding=_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  ).input_values
         self.assertTrue(input_values.ndim == 3  )
         self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins  )

         # Test not batched input
         UpperCAmelCase_      :							Optional[Any]       =      feature_extractor(speech_inputs[0]       ,return_tensors='''np'''  ).input_values
         UpperCAmelCase_      :							int       =      feature_extractor(np_speech_inputs[0]       ,return_tensors='''np'''  ).input_values
         self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,atol=1e-3  )  )

         # Test batched
         UpperCAmelCase_      :							Any       =      feature_extractor(_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  ).input_values
         UpperCAmelCase_      :							List[str]       =      feature_extractor(_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  ).input_values
         for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ):
              self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,atol=1e-3  )  )

         # Test 2-D numpy arrays are batched.
         UpperCAmelCase_      :							Any       =      [floats_list((1, x)  )[0] for x in (800, 800, 800)]
         UpperCAmelCase_      :							Optional[int]       =      np.asarray(_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							List[str]       =      feature_extractor(_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  ).input_values
         UpperCAmelCase_      :							str       =      feature_extractor(_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  ).input_values
         for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  ):
              self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,atol=1e-3  )  )





    def 							a__				(				self  )			->		Optional[int]:
         UpperCAmelCase_      :							Union[str, Any]       =      self.feat_extract_tester.prepare_inputs_for_target()
         UpperCAmelCase_      :							Union[str, Any]       =      self.feature_extraction_class(**self.feat_extract_dict  )
         UpperCAmelCase_      :							str       =      feat_extract.model_input_names[0]

         UpperCAmelCase_      :							List[str]       =      BatchFeature({input_name: speech_inputs}  )

         self.assertTrue(all(len(_SCREAMING_SNAKE_CASE  ) == len(_SCREAMING_SNAKE_CASE  ) for x, y in zip(_SCREAMING_SNAKE_CASE       ,processed_features[input_name]  )  )  )

         UpperCAmelCase_      :							Dict       =      self.feat_extract_tester.prepare_inputs_for_target(equal_length=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Dict       =      BatchFeature({input_name: speech_inputs}       ,tensor_type='''np'''  )

         UpperCAmelCase_      :							Optional[int]       =      processed_features[input_name]

         if len(batch_features_input.shape  ) < 3:
              UpperCAmelCase_      :							Any       =      batch_features_input[:, :, None]

         self.assertTrue(
             batch_features_input.shape
             == (self.feat_extract_tester.batch_size, len(speech_inputs[0]  ), self.feat_extract_tester.num_mel_bins)  )





    @require_torch
    def 							a__				(				self  )			->		str:
         UpperCAmelCase_      :							List[str]       =      self.feat_extract_tester.prepare_inputs_for_target(equal_length=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Any       =      self.feature_extraction_class(**self.feat_extract_dict  )
         UpperCAmelCase_      :							str       =      feat_extract.model_input_names[0]

         UpperCAmelCase_      :							Union[str, Any]       =      BatchFeature({input_name: speech_inputs}       ,tensor_type='''pt'''  )

         UpperCAmelCase_      :							str       =      processed_features[input_name]

         if len(batch_features_input.shape  ) < 3:
              UpperCAmelCase_      :							List[str]       =      batch_features_input[:, :, None]

         self.assertTrue(
             batch_features_input.shape
             == (self.feat_extract_tester.batch_size, len(speech_inputs[0]  ), self.feat_extract_tester.num_mel_bins)  )





    @require_torch
    def 							a__				(				self  )			->		Optional[Any]:
         UpperCAmelCase_      :							Optional[int]       =      self.feature_extraction_class(**self.feat_extract_dict  )
         UpperCAmelCase_      :							List[str]       =      self.feat_extract_tester.prepare_inputs_for_target()
         UpperCAmelCase_      :							str       =      feat_extract.model_input_names[0]

         UpperCAmelCase_      :							List[str]       =      BatchFeature({input_name: speech_inputs}  )

         UpperCAmelCase_      :							Any       =      feat_extract.num_mel_bins  # hack!

         UpperCAmelCase_      :							List[str]       =      feat_extract.pad(_SCREAMING_SNAKE_CASE       ,padding='''longest'''       ,return_tensors='''np'''  )[input_name]
         UpperCAmelCase_      :							str       =      feat_extract.pad(_SCREAMING_SNAKE_CASE       ,padding='''longest'''       ,return_tensors='''pt'''  )[input_name]

         self.assertTrue(abs(input_np.astype(np.floataa  ).sum() - input_pt.numpy().astype(np.floataa  ).sum()  ) < 1e-2  )





    def 							a__				(				self  )			->		Union[str, Any]:
         UpperCAmelCase_      :							Any       =      self.feat_extract_dict
         UpperCAmelCase_      :							Any       =      True
         UpperCAmelCase_      :							List[Any]       =      self.feature_extraction_class(**_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							str       =      self.feat_extract_tester.prepare_inputs_for_target()
         UpperCAmelCase_      :							Dict       =      [len(_SCREAMING_SNAKE_CASE  ) for x in speech_inputs]
         UpperCAmelCase_      :							List[str]       =      feat_extract.model_input_names[0]

         UpperCAmelCase_      :							Dict       =      BatchFeature({input_name: speech_inputs}  )

         UpperCAmelCase_      :							int       =      feat_extract.num_mel_bins  # hack!

         UpperCAmelCase_      :							Optional[Any]       =      feat_extract.pad(_SCREAMING_SNAKE_CASE       ,padding='''longest'''       ,return_tensors='''np'''  )
         self.assertIn('''attention_mask'''       ,_SCREAMING_SNAKE_CASE  )
         self.assertListEqual(list(processed.attention_mask.shape  )       ,list(processed[input_name].shape[:2]  )  )
         self.assertListEqual(processed.attention_mask.sum(-1  ).tolist()       ,_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Optional[int]:
         UpperCAmelCase_      :							Tuple       =      self.feat_extract_dict
         UpperCAmelCase_      :							str       =      True
         UpperCAmelCase_      :							Any       =      self.feature_extraction_class(**_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Dict       =      self.feat_extract_tester.prepare_inputs_for_target()
         UpperCAmelCase_      :							Dict       =      [len(_SCREAMING_SNAKE_CASE  ) for x in speech_inputs]
         UpperCAmelCase_      :							List[Any]       =      feat_extract.model_input_names[0]

         UpperCAmelCase_      :							List[Any]       =      BatchFeature({input_name: speech_inputs}  )
         UpperCAmelCase_      :							Any       =      min(_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							List[Any]       =      feat_extract.num_mel_bins  # hack!

         UpperCAmelCase_      :							Optional[int]       =      feat_extract.pad(
             _SCREAMING_SNAKE_CASE       ,padding='''max_length'''       ,max_length=_SCREAMING_SNAKE_CASE       ,truncation=_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  )
         self.assertIn('''attention_mask'''       ,_SCREAMING_SNAKE_CASE  )
         self.assertListEqual(
             list(processed_pad.attention_mask.shape  )       ,[processed_pad[input_name].shape[0], max_length]  )
         self.assertListEqual(
             processed_pad.attention_mask[:, :max_length].sum(-1  ).tolist()       ,[max_length for x in speech_inputs]  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE  )			->		str:
         from datasets import load_dataset

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

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





    def 							a__				(				self  )			->		Optional[Any]:
         # fmt: off
         UpperCAmelCase_      :							List[str]       =      torch.tensor(
             [2.38_04e-03, 2.07_52e-03, 1.98_36e-03, 2.10_57e-03, 1.61_74e-03,
              3.05_18e-04, 9.15_53e-05, 3.35_69e-04, 9.76_56e-04, 1.83_11e-03,
              2.01_42e-03, 2.10_57e-03, 1.73_95e-03, 4.57_76e-04, -3.96_73e-04,
              4.57_76e-04, 1.00_71e-03, 9.15_53e-05, 4.88_28e-04, 1.15_97e-03,
              7.32_42e-04, 9.46_04e-04, 1.80_05e-03, 1.83_11e-03, 8.85_01e-04,
              4.27_25e-04, 4.88_28e-04, 7.32_42e-04, 1.09_86e-03, 2.10_57e-03]  )
         # fmt: on

         UpperCAmelCase_      :							Union[str, Any]       =      self._load_datasamples(1  )
         UpperCAmelCase_      :							List[str]       =      SpeechTaFeatureExtractor()
         UpperCAmelCase_      :							List[Any]       =      feature_extractor(_SCREAMING_SNAKE_CASE       ,return_tensors='''pt'''  ).input_values
         self.assertEquals(input_values.shape       ,(1, 93_680)  )
         self.assertTrue(torch.allclose(input_values[0, :30]       ,_SCREAMING_SNAKE_CASE       ,atol=1e-6  )  )





    def 							a__				(				self  )			->		List[str]:
         # fmt: off
         UpperCAmelCase_      :							Union[str, Any]       =      torch.tensor(
             [-2.68_70, -3.01_04, -3.13_56, -3.53_52, -3.00_44, -3.03_53, -3.47_19, -3.67_77,
              -3.15_20, -2.94_35, -2.65_53, -2.87_95, -2.99_44, -2.59_21, -3.02_79, -3.03_86,
              -3.08_64, -3.12_91, -3.23_53, -2.74_44, -2.68_31, -2.72_87, -3.17_61, -3.15_71,
              -3.27_26, -3.05_82, -3.10_07, -3.45_33, -3.46_95, -3.09_98]  )
         # fmt: on

         UpperCAmelCase_      :							List[Any]       =      self._load_datasamples(1  )
         UpperCAmelCase_      :							Tuple       =      SpeechTaFeatureExtractor()
         UpperCAmelCase_      :							Dict       =      feature_extractor(audio_target=_SCREAMING_SNAKE_CASE       ,return_tensors='''pt'''  ).input_values
         self.assertEquals(input_values.shape       ,(1, 366, 80)  )
         self.assertTrue(torch.allclose(input_values[0, 0, :30]       ,_SCREAMING_SNAKE_CASE       ,atol=1e-4  )  )





import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available


if is_vision_available():
     from PIL import Image

     from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast

@require_vision
class   __a(					unittest.TestCase       ):






    """simple docstring"""





    def 							a__				(				self  )			->		Optional[int]:
         UpperCAmelCase_      :							Optional[int]       =      tempfile.mkdtemp()

         UpperCAmelCase_      :							str       =      BlipImageProcessor()
         UpperCAmelCase_      :							Dict       =      GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model'''  )

         UpperCAmelCase_      :							Optional[Any]       =      BlipaProcessor(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )

         processor.save_pretrained(self.tmpdirname  )





    def 							a__				(				self       ,**_SCREAMING_SNAKE_CASE  )			->		Optional[int]:
         return AutoProcessor.from_pretrained(self.tmpdirname       ,**_SCREAMING_SNAKE_CASE  ).tokenizer





    def 							a__				(				self       ,**_SCREAMING_SNAKE_CASE  )			->		Dict:
         return AutoProcessor.from_pretrained(self.tmpdirname       ,**_SCREAMING_SNAKE_CASE  ).image_processor





    def 							a__				(				self  )			->		List[Any]:
         shutil.rmtree(self.tmpdirname  )





    def 							a__				(				self  )			->		Tuple:
         UpperCAmelCase_      :							Tuple       =      [np.random.randint(255       ,size=(3, 30, 400)       ,dtype=np.uinta  )]

         UpperCAmelCase_      :							Optional[Any]       =      [Image.fromarray(np.moveaxis(_SCREAMING_SNAKE_CASE       ,0       ,-1  )  ) for x in image_inputs]

         return image_inputs





    def 							a__				(				self  )			->		List[str]:
         UpperCAmelCase_      :							Dict       =      BlipaProcessor(tokenizer=self.get_tokenizer()       ,image_processor=self.get_image_processor()  )
         processor.save_pretrained(self.tmpdirname  )

         UpperCAmelCase_      :							str       =      self.get_tokenizer(bos_token='''(BOS)'''       ,eos_token='''(EOS)'''  )
         UpperCAmelCase_      :							int       =      self.get_image_processor(do_normalize=_SCREAMING_SNAKE_CASE       ,padding_value=1.0  )

         UpperCAmelCase_      :							Union[str, Any]       =      BlipaProcessor.from_pretrained(
             self.tmpdirname       ,bos_token='''(BOS)'''       ,eos_token='''(EOS)'''       ,do_normalize=_SCREAMING_SNAKE_CASE       ,padding_value=1.0  )

         self.assertEqual(processor.tokenizer.get_vocab()       ,tokenizer_add_kwargs.get_vocab()  )
         self.assertIsInstance(processor.tokenizer       ,_SCREAMING_SNAKE_CASE  )

         self.assertEqual(processor.image_processor.to_json_string()       ,image_processor_add_kwargs.to_json_string()  )
         self.assertIsInstance(processor.image_processor       ,_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		Any:
         UpperCAmelCase_      :							Dict       =      self.get_image_processor()
         UpperCAmelCase_      :							Any       =      self.get_tokenizer()

         UpperCAmelCase_      :							str       =      BlipaProcessor(tokenizer=_SCREAMING_SNAKE_CASE       ,image_processor=_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Union[str, Any]       =      self.prepare_image_inputs()

         UpperCAmelCase_      :							Optional[Any]       =      image_processor(_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  )
         UpperCAmelCase_      :							int       =      processor(images=_SCREAMING_SNAKE_CASE       ,return_tensors='''np'''  )

         for key in input_feat_extract.keys():
              self.assertAlmostEqual(input_feat_extract[key].sum()       ,input_processor[key].sum()       ,delta=1e-2  )





    def 							a__				(				self  )			->		int:
         UpperCAmelCase_      :							str       =      self.get_image_processor()
         UpperCAmelCase_      :							List[Any]       =      self.get_tokenizer()

         UpperCAmelCase_      :							Any       =      BlipaProcessor(tokenizer=_SCREAMING_SNAKE_CASE       ,image_processor=_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Tuple       =      '''lower newer'''

         UpperCAmelCase_      :							Optional[int]       =      processor(text=_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							int       =      tokenizer(_SCREAMING_SNAKE_CASE       ,return_token_type_ids=_SCREAMING_SNAKE_CASE  )

         for key in encoded_tok.keys():
              self.assertListEqual(encoded_tok[key]       ,encoded_processor[key]  )





    def 							a__				(				self  )			->		Optional[int]:
         UpperCAmelCase_      :							str       =      self.get_image_processor()
         UpperCAmelCase_      :							List[Any]       =      self.get_tokenizer()

         UpperCAmelCase_      :							Tuple       =      BlipaProcessor(tokenizer=_SCREAMING_SNAKE_CASE       ,image_processor=_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							int       =      '''lower newer'''
         UpperCAmelCase_      :							int       =      self.prepare_image_inputs()

         UpperCAmelCase_      :							List[str]       =      processor(text=_SCREAMING_SNAKE_CASE       ,images=_SCREAMING_SNAKE_CASE  )

         self.assertListEqual(list(inputs.keys()  )       ,['''pixel_values''', '''input_ids''', '''attention_mask''']  )

         # test if it raises when no input is passed
         with pytest.raises(_SCREAMING_SNAKE_CASE  ):
              processor()





    def 							a__				(				self  )			->		Optional[int]:
         UpperCAmelCase_      :							Tuple       =      self.get_image_processor()
         UpperCAmelCase_      :							Dict       =      self.get_tokenizer()

         UpperCAmelCase_      :							List[str]       =      BlipaProcessor(tokenizer=_SCREAMING_SNAKE_CASE       ,image_processor=_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Optional[Any]       =      [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

         UpperCAmelCase_      :							List[str]       =      processor.batch_decode(_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Union[str, Any]       =      tokenizer.batch_decode(_SCREAMING_SNAKE_CASE  )

         self.assertListEqual(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self  )			->		str:
         UpperCAmelCase_      :							Union[str, Any]       =      self.get_image_processor()
         UpperCAmelCase_      :							int       =      self.get_tokenizer()

         UpperCAmelCase_      :							Any       =      BlipaProcessor(tokenizer=_SCREAMING_SNAKE_CASE       ,image_processor=_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Dict       =      '''lower newer'''
         UpperCAmelCase_      :							Union[str, Any]       =      self.prepare_image_inputs()

         UpperCAmelCase_      :							Any       =      processor(text=_SCREAMING_SNAKE_CASE       ,images=_SCREAMING_SNAKE_CASE  )

         # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
         self.assertListEqual(list(inputs.keys()  )       ,['''pixel_values''', '''input_ids''', '''attention_mask''']  )