




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


lowerCamelCase	:	List[Any]				=   random.Random()




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase=1.0						,lowercase=None						,lowercase=None					)  ->       List[Any]:
   if rng is None:
      snake_case				:    Optional[Any]           =	global_rng

   snake_case				:    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
class 						__lowercase		(unittest.TestCase							):




      """simple docstring"""





      def __init__(				self    ,				A    ,				A=7    ,				A=4_0_0    ,				A=2_0_0_0    ,				A=1    ,				A=0.0    ,				A=1_6_0_0_0    ,				A=True    ,				A=8_0    ,				A=1_6    ,				A=6_4    ,				A="hann_window"    ,				A=8_0    ,				A=7_6_0_0    ,				A=1e-1_0    ,				A=True    ,				)		->    List[str]:
         snake_case				:    List[str]           =	parent
         snake_case				:    Optional[Any]           =	batch_size
         snake_case				:    int           =	min_seq_length
         snake_case				:    Tuple           =	max_seq_length
         snake_case				:    List[Any]           =	(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
         snake_case				:    Any           =	feature_size
         snake_case				:    str           =	padding_value
         snake_case				:    Tuple           =	sampling_rate
         snake_case				:    Optional[Any]           =	do_normalize
         snake_case				:    List[Any]           =	num_mel_bins
         snake_case				:    Optional[Any]           =	hop_length
         snake_case				:    Any           =	win_length
         snake_case				:    Any           =	win_function
         snake_case				:    List[str]           =	fmin
         snake_case				:    Dict           =	fmax
         snake_case				:    Tuple           =	mel_floor
         snake_case				:    Optional[Any]           =	return_attention_mask

      def      UpperCAmelCase				(				self     )		->    List[str]:
         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      UpperCAmelCase				(				self    ,				A=False    ,				A=False     )		->    str:
         def _flatten(A     ):
            return list(itertools.chain(*A     )     )

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

         return speech_inputs

      def      UpperCAmelCase				(				self    ,				A=False    ,				A=False     )		->    int:
         if equal_length:
            snake_case				:    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
            snake_case				:    Dict           =	[
                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:
            snake_case				:    Union[str, Any]           =	[np.asarray(A     ) for x in speech_inputs]

         return speech_inputs




@require_torch
class 						__lowercase		(UpperCamelCase__					,		unittest.TestCase							):




      """simple docstring"""





      _snake_case												=						SpeechTaFeatureExtractor

      def      UpperCAmelCase				(				self     )		->    Tuple:
         snake_case				:    List[Any]           =	SpeechTaFeatureExtractionTester(self     )

      def      UpperCAmelCase				(				self    ,				A     )		->    str:
         self.assertTrue(np.all(np.mean(A    ,				axis=0     ) < 1e-3     )     )
         self.assertTrue(np.all(np.abs(np.var(A    ,				axis=0     ) - 1     ) < 1e-3     )     )

      def      UpperCAmelCase				(				self     )		->    Optional[Any]:
         # Tests that all call wrap to encode_plus and batch_encode_plus
         snake_case				:    Optional[Any]           =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
         # create three inputs of length 800, 1000, and 1200
         snake_case				:    Tuple           =	[floats_list((1, x)     )[0] for x in range(8_0_0    ,				1_4_0_0    ,				2_0_0     )]
         snake_case				:    str           =	[np.asarray(A     ) for speech_input in speech_inputs]

         # Test not batched input
         snake_case				:    Optional[Any]           =	feat_extract(speech_inputs[0]    ,				return_tensors="""np"""     ).input_values
         snake_case				:    List[Any]           =	feat_extract(np_speech_inputs[0]    ,				return_tensors="""np"""     ).input_values
         self.assertTrue(np.allclose(A    ,				A    ,				atol=1e-3     )     )

         # Test batched
         snake_case				:    Optional[int]           =	feat_extract(A    ,				return_tensors="""np"""     ).input_values
         snake_case				:    List[str]           =	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     )     )

      def      UpperCAmelCase				(				self     )		->    Optional[int]:
         snake_case				:    Tuple           =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
         snake_case				:    List[Any]           =	[floats_list((1, x)     )[0] for x in range(8_0_0    ,				1_4_0_0    ,				2_0_0     )]

         snake_case				:    str           =	["""longest""", """max_length""", """do_not_pad"""]
         snake_case				:    Union[str, Any]           =	[None, 1_6_0_0, None]
         for max_length, padding in zip(A    ,				A     ):
            snake_case				:    Union[str, Any]           =	feat_extract(A    ,				padding=A    ,				max_length=A    ,				return_tensors="""np"""     )
            snake_case				:    str           =	processed.input_values

            self._check_zero_mean_unit_variance(input_values[0][:8_0_0]     )
            self.assertTrue(input_values[0][8_0_0:].sum() < 1e-6     )
            self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0]     )
            self.assertTrue(input_values[0][1_0_0_0:].sum() < 1e-6     )
            self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0]     )

      def      UpperCAmelCase				(				self     )		->    Any:
         snake_case				:    Union[str, Any]           =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
         snake_case				:    Tuple           =	range(8_0_0    ,				1_4_0_0    ,				2_0_0     )
         snake_case				:    Union[str, Any]           =	[floats_list((1, x)     )[0] for x in lengths]

         snake_case				:    str           =	["""longest""", """max_length""", """do_not_pad"""]
         snake_case				:    str           =	[None, 1_6_0_0, None]

         for max_length, padding in zip(A    ,				A     ):
            snake_case				:    Tuple           =	feat_extract(A    ,				max_length=A    ,				padding=A     )
            snake_case				:    int           =	processed.input_values

            self._check_zero_mean_unit_variance(input_values[0][:8_0_0]     )
            self._check_zero_mean_unit_variance(input_values[1][:1_0_0_0]     )
            self._check_zero_mean_unit_variance(input_values[2][:1_2_0_0]     )

      def      UpperCAmelCase				(				self     )		->    Optional[Any]:
         snake_case				:    int           =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
         snake_case				:    List[str]           =	[floats_list((1, x)     )[0] for x in range(8_0_0    ,				1_4_0_0    ,				2_0_0     )]
         snake_case				:    str           =	feat_extract(
             A    ,				truncation=A    ,				max_length=1_0_0_0    ,				padding="""max_length"""    ,				return_tensors="""np"""     )
         snake_case				:    Any           =	processed.input_values

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

      def      UpperCAmelCase				(				self     )		->    int:
         snake_case				:    int           =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
         snake_case				:    Tuple           =	[floats_list((1, x)     )[0] for x in range(8_0_0    ,				1_4_0_0    ,				2_0_0     )]
         snake_case				:    Optional[int]           =	feat_extract(
             A    ,				truncation=A    ,				max_length=1_0_0_0    ,				padding="""longest"""    ,				return_tensors="""np"""     )
         snake_case				:    Any           =	processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :8_0_0]     )
         self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0]     )
         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_0_0_0)     )

         snake_case				:    Dict           =	[floats_list((1, x)     )[0] for x in range(8_0_0    ,				1_4_0_0    ,				2_0_0     )]
         snake_case				:    List[str]           =	feat_extract(
             A    ,				truncation=A    ,				max_length=2_0_0_0    ,				padding="""longest"""    ,				return_tensors="""np"""     )
         snake_case				:    Any           =	processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :8_0_0]     )
         self._check_zero_mean_unit_variance(input_values[1, :1_0_0_0]     )
         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_2_0_0)     )

      def      UpperCAmelCase				(				self     )		->    str:
         snake_case				:    str           =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
         snake_case				:    List[Any]           =	np.random.rand(1_0_0     ).astype(np.floataa     )
         snake_case				:    str           =	np_speech_inputs.tolist()

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

      def      UpperCAmelCase				(				self     )		->    List[str]:
         # Tests that all call wrap to encode_plus and batch_encode_plus
         snake_case				:    int           =	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()     )
         # create three inputs of length 800, 1000, and 1200
         snake_case				:    List[Any]           =	[floats_list((1, x)     )[0] for x in range(8_0_0    ,				1_4_0_0    ,				2_0_0     )]
         snake_case				:    Union[str, Any]           =	[np.asarray(A     ) for speech_input in speech_inputs]

         # Test feature size
         snake_case				:    Union[str, Any]           =	feature_extractor(audio_target=A    ,				padding=A    ,				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
         snake_case				:    int           =	feature_extractor(speech_inputs[0]    ,				return_tensors="""np"""     ).input_values
         snake_case				:    Optional[int]           =	feature_extractor(np_speech_inputs[0]    ,				return_tensors="""np"""     ).input_values
         self.assertTrue(np.allclose(A    ,				A    ,				atol=1e-3     )     )

         # Test batched
         snake_case				:    List[Any]           =	feature_extractor(A    ,				return_tensors="""np"""     ).input_values
         snake_case				:    Optional[Any]           =	feature_extractor(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.
         snake_case				:    Any           =	[floats_list((1, x)     )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
         snake_case				:    List[Any]           =	np.asarray(A     )
         snake_case				:    str           =	feature_extractor(A    ,				return_tensors="""np"""     ).input_values
         snake_case				:    Optional[Any]           =	feature_extractor(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     )     )

      def      UpperCAmelCase				(				self     )		->    Dict:
         snake_case				:    List[str]           =	self.feat_extract_tester.prepare_inputs_for_target()
         snake_case				:    Optional[int]           =	self.feature_extraction_class(**self.feat_extract_dict     )
         snake_case				:    List[Any]           =	feat_extract.model_input_names[0]

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

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

         snake_case				:    List[str]           =	self.feat_extract_tester.prepare_inputs_for_target(equal_length=A     )
         snake_case				:    Dict           =	BatchFeature({input_name: speech_inputs}    ,				tensor_type="""np"""     )

         snake_case				:    Tuple           =	processed_features[input_name]

         if len(batch_features_input.shape     ) < 3:
            snake_case				:    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      UpperCAmelCase				(				self     )		->    List[str]:
         snake_case				:    Any           =	self.feat_extract_tester.prepare_inputs_for_target(equal_length=A     )
         snake_case				:    str           =	self.feature_extraction_class(**self.feat_extract_dict     )
         snake_case				:    Optional[Any]           =	feat_extract.model_input_names[0]

         snake_case				:    Dict           =	BatchFeature({input_name: speech_inputs}    ,				tensor_type="""pt"""     )

         snake_case				:    Tuple           =	processed_features[input_name]

         if len(batch_features_input.shape     ) < 3:
            snake_case				:    int           =	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      UpperCAmelCase				(				self     )		->    Tuple:
         snake_case				:    Union[str, Any]           =	self.feature_extraction_class(**self.feat_extract_dict     )
         snake_case				:    str           =	self.feat_extract_tester.prepare_inputs_for_target()
         snake_case				:    Optional[int]           =	feat_extract.model_input_names[0]

         snake_case				:    str           =	BatchFeature({input_name: speech_inputs}     )

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

         snake_case				:    List[Any]           =	feat_extract.pad(A    ,				padding="""longest"""    ,				return_tensors="""np"""     )[input_name]
         snake_case				:    Tuple           =	feat_extract.pad(A    ,				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      UpperCAmelCase				(				self     )		->    List[str]:
         snake_case				:    List[str]           =	self.feat_extract_dict
         snake_case				:    Dict           =	True
         snake_case				:    str           =	self.feature_extraction_class(**A     )
         snake_case				:    Tuple           =	self.feat_extract_tester.prepare_inputs_for_target()
         snake_case				:    List[str]           =	[len(A     ) for x in speech_inputs]
         snake_case				:    Union[str, Any]           =	feat_extract.model_input_names[0]

         snake_case				:    Optional[int]           =	BatchFeature({input_name: speech_inputs}     )

         snake_case				:    int           =	feat_extract.num_mel_bins  # hack!

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

      def      UpperCAmelCase				(				self     )		->    Optional[Any]:
         snake_case				:    Any           =	self.feat_extract_dict
         snake_case				:    List[str]           =	True
         snake_case				:    Dict           =	self.feature_extraction_class(**A     )
         snake_case				:    Union[str, Any]           =	self.feat_extract_tester.prepare_inputs_for_target()
         snake_case				:    Union[str, Any]           =	[len(A     ) for x in speech_inputs]
         snake_case				:    Tuple           =	feat_extract.model_input_names[0]

         snake_case				:    Tuple           =	BatchFeature({input_name: speech_inputs}     )
         snake_case				:    List[Any]           =	min(A     )

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

         snake_case				:    Dict           =	feat_extract.pad(
             A    ,				padding="""max_length"""    ,				max_length=A    ,				truncation=A    ,				return_tensors="""np"""     )
         self.assertIn("""attention_mask"""    ,				A     )
         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      UpperCAmelCase				(				self    ,				A     )		->    int:
         from datasets import load_dataset

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

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

      def      UpperCAmelCase				(				self     )		->    Any:
         # fmt: off
         snake_case				:    List[str]           =	torch.tensor(
             [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3,
              3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3,
              2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4,
              4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3,
              7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4,
              4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3]     )
         # fmt: on

         snake_case				:    str           =	self._load_datasamples(1     )
         snake_case				:    Optional[int]           =	SpeechTaFeatureExtractor()
         snake_case				:    Optional[int]           =	feature_extractor(A    ,				return_tensors="""pt"""     ).input_values
         self.assertEquals(input_values.shape    ,				(1, 9_3_6_8_0)     )
         self.assertTrue(torch.allclose(input_values[0, :3_0]    ,				A    ,				atol=1e-6     )     )

      def      UpperCAmelCase				(				self     )		->    List[Any]:
         # fmt: off
         snake_case				:    Optional[int]           =	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

         snake_case				:    str           =	self._load_datasamples(1     )
         snake_case				:    Any           =	SpeechTaFeatureExtractor()
         snake_case				:    List[Any]           =	feature_extractor(audio_target=A    ,				return_tensors="""pt"""     ).input_values
         self.assertEquals(input_values.shape    ,				(1, 3_6_6, 8_0)     )
         self.assertTrue(torch.allclose(input_values[0, 0, :3_0]    ,				A    ,				atol=1e-4     )     )











def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase					)  ->       int:
   return int((input_a, input_a).count(1					) != 0					)




def 						SCREAMING_SNAKE_CASE__ (   )  ->       None:
   assert or_gate(0						,0					) == 0
   assert or_gate(0						,1					) == 1
   assert or_gate(1						,0					) == 1
   assert or_gate(1						,1					) == 1


if __name__ == "__main__":
       print(or_gate(0, 1))
       print(or_gate(1, 0))
       print(or_gate(0, 0))
       print(or_gate(1, 1))





