






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__							=     random.Random()






def   UpperCamelCase  (       snake_case__     :   Optional[int]	,snake_case__     :   Dict=1.0	,snake_case__     :   Any=None	,snake_case__     :   Optional[int]=None  ):




     '''simple docstring'''






     if rng is None:
          __snake_case			:int          =						global_rng

     __snake_case			:str          =						[]
     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 			snake_case__   (							unittest.TestCase):

       '''simple docstring'''



       def __init__(							self			,						a__			,						a__=7			,						a__=4_00			,						a__=20_00			,						a__=1			,						a__=0.0			,						a__=1_60_00			,						a__=True			,						a__=80			,						a__=16			,						a__=64			,						a__="hann_window"			,						a__=80			,						a__=76_00			,						a__=1e-10			,						a__=True			,						) ->      str:






            '''simple docstring'''





            __snake_case			:Tuple          =						parent
            __snake_case			:Union[str, Any]          =						batch_size
            __snake_case			:int          =						min_seq_length
            __snake_case			:int          =						max_seq_length
            __snake_case			:Any          =						(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
            __snake_case			:Any          =						feature_size
            __snake_case			:Optional[Any]          =						padding_value
            __snake_case			:Tuple          =						sampling_rate
            __snake_case			:int          =						do_normalize
            __snake_case			:Dict          =						num_mel_bins
            __snake_case			:List[str]          =						hop_length
            __snake_case			:List[str]          =						win_length
            __snake_case			:List[str]          =						win_function
            __snake_case			:List[str]          =						fmin
            __snake_case			:Union[str, Any]          =						fmax
            __snake_case			:List[Any]          =						mel_floor
            __snake_case			:Optional[int]          =						return_attention_mask



       def 					__lowercase						(							self    ) ->      Tuple:






            '''simple docstring'''





            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 					__lowercase						(							self			,						a__=False			,						a__=False    ) ->      Tuple:






            '''simple docstring'''





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

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

            return speech_inputs



       def 					__lowercase						(							self			,						a__=False			,						a__=False    ) ->      Any:






            '''simple docstring'''





            if equal_length:
                 __snake_case			: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 			snake_case__   (							lowercase_	,    unittest.TestCase):

       '''simple docstring'''
       lowerCamelCase							:				Dict 				= SpeechTaFeatureExtractor



       def 					__lowercase						(							self    ) ->      Union[str, Any]:






            '''simple docstring'''





            __snake_case			:str          =						SpeechTaFeatureExtractionTester(self    )



       def 					__lowercase						(							self			,						a__    ) ->      Tuple:






            '''simple docstring'''





            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 					__lowercase						(							self    ) ->      Union[str, Any]:






            '''simple docstring'''





            __snake_case			:Tuple          =						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
            # create three inputs of length 800, 1000, and 1200
            __snake_case			:Optional[Any]          =						[floats_list((1, x)    )[0] for x in range(8_00			,						14_00			,						2_00    )]
            __snake_case			:List[Any]          =						[np.asarray(a__    ) for speech_input in speech_inputs]

            # Test not batched input
            __snake_case			:Union[str, Any]          =						feat_extract(speech_inputs[0]			,						return_tensors="""np"""    ).input_values
            __snake_case			:Optional[int]          =						feat_extract(np_speech_inputs[0]			,						return_tensors="""np"""    ).input_values
            self.assertTrue(np.allclose(a__			,						a__			,						atol=1e-3    )    )

            # Test batched
            __snake_case			:Dict          =						feat_extract(a__			,						return_tensors="""np"""    ).input_values
            __snake_case			:int          =						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 					__lowercase						(							self    ) ->      Union[str, Any]:






            '''simple docstring'''





            __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_00			,						14_00			,						2_00    )]

            __snake_case			:Any          =						["""longest""", """max_length""", """do_not_pad"""]
            __snake_case			:List[str]          =						[None, 16_00, None]
            for max_length, padding in zip(a__			,						a__    ):
                 __snake_case			:Any          =						feat_extract(a__			,						padding=a__			,						max_length=a__			,						return_tensors="""np"""    )
                 __snake_case			:int          =						processed.input_values

                 self._check_zero_mean_unit_variance(input_values[0][:8_00]    )
                 self.assertTrue(input_values[0][8_00:].sum() < 1e-6    )
                 self._check_zero_mean_unit_variance(input_values[1][:10_00]    )
                 self.assertTrue(input_values[0][10_00:].sum() < 1e-6    )
                 self._check_zero_mean_unit_variance(input_values[2][:12_00]    )



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            __snake_case			:Union[str, Any]          =						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
            __snake_case			:Optional[int]          =						range(8_00			,						14_00			,						2_00    )
            __snake_case			:Dict          =						[floats_list((1, x)    )[0] for x in lengths]

            __snake_case			:Tuple          =						["""longest""", """max_length""", """do_not_pad"""]
            __snake_case			:List[str]          =						[None, 16_00, None]

            for max_length, padding in zip(a__			,						a__    ):
                 __snake_case			:Union[str, Any]          =						feat_extract(a__			,						max_length=a__			,						padding=a__    )
                 __snake_case			:Dict          =						processed.input_values

                 self._check_zero_mean_unit_variance(input_values[0][:8_00]    )
                 self._check_zero_mean_unit_variance(input_values[1][:10_00]    )
                 self._check_zero_mean_unit_variance(input_values[2][:12_00]    )



       def 					__lowercase						(							self    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:int          =						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
            __snake_case			:str          =						[floats_list((1, x)    )[0] for x in range(8_00			,						14_00			,						2_00    )]
            __snake_case			:Tuple          =						feat_extract(
                a__			,						truncation=a__			,						max_length=10_00			,						padding="""max_length"""			,						return_tensors="""np"""    )
            __snake_case			:int          =						processed.input_values

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



       def 					__lowercase						(							self    ) ->      int:






            '''simple docstring'''





            __snake_case			:str          =						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_00			,						14_00			,						2_00    )]
            __snake_case			:List[Any]          =						feat_extract(
                a__			,						truncation=a__			,						max_length=10_00			,						padding="""longest"""			,						return_tensors="""np"""    )
            __snake_case			:Optional[int]          =						processed.input_values

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

            __snake_case			:Union[str, Any]          =						[floats_list((1, x)    )[0] for x in range(8_00			,						14_00			,						2_00    )]
            __snake_case			:Optional[Any]          =						feat_extract(
                a__			,						truncation=a__			,						max_length=20_00			,						padding="""longest"""			,						return_tensors="""np"""    )
            __snake_case			:Dict          =						processed.input_values

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



       def 					__lowercase						(							self    ) ->      Union[str, Any]:






            '''simple docstring'''





            __snake_case			:Optional[Any]          =						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
            __snake_case			:int          =						np.random.rand(1_00    ).astype(np.floataa    )
            __snake_case			:List[Any]          =						np_speech_inputs.tolist()

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



       def 					__lowercase						(							self    ) ->      Optional[Any]:






            '''simple docstring'''





            __snake_case			:Tuple          =						self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()    )
            # create three inputs of length 800, 1000, and 1200
            __snake_case			:Optional[int]          =						[floats_list((1, x)    )[0] for x in range(8_00			,						14_00			,						2_00    )]
            __snake_case			:Dict          =						[np.asarray(a__    ) for speech_input in speech_inputs]

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

            # Test batched
            __snake_case			:int          =						feature_extractor(a__			,						return_tensors="""np"""    ).input_values
            __snake_case			:Tuple          =						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			:Union[str, Any]          =						[floats_list((1, x)    )[0] for x in (8_00, 8_00, 8_00)]
            __snake_case			:str          =						np.asarray(a__    )
            __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    )    )



       def 					__lowercase						(							self    ) ->      Union[str, Any]:






            '''simple docstring'''





            __snake_case			:List[str]          =						self.feat_extract_tester.prepare_inputs_for_target()
            __snake_case			:Dict          =						self.feature_extraction_class(**self.feat_extract_dict    )
            __snake_case			:Union[str, Any]          =						feat_extract.model_input_names[0]

            __snake_case			: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			:Any          =						BatchFeature({input_name: speech_inputs}			,						tensor_type="""np"""    )

            __snake_case			:Optional[int]          =						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 					__lowercase						(							self    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:Dict          =						self.feat_extract_tester.prepare_inputs_for_target(equal_length=a__    )
            __snake_case			:Tuple          =						self.feature_extraction_class(**self.feat_extract_dict    )
            __snake_case			:Any          =						feat_extract.model_input_names[0]

            __snake_case			:str          =						BatchFeature({input_name: speech_inputs}			,						tensor_type="""pt"""    )

            __snake_case			:List[str]          =						processed_features[input_name]

            if len(batch_features_input.shape    ) < 3:
                 __snake_case			:List[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 					__lowercase						(							self    ) ->      Union[str, Any]:






            '''simple docstring'''





            __snake_case			:Dict          =						self.feature_extraction_class(**self.feat_extract_dict    )
            __snake_case			:Union[str, Any]          =						self.feat_extract_tester.prepare_inputs_for_target()
            __snake_case			:Optional[Any]          =						feat_extract.model_input_names[0]

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

            __snake_case			:Dict          =						feat_extract.num_mel_bins  # hack!

            __snake_case			:Any          =						feat_extract.pad(a__			,						padding="""longest"""			,						return_tensors="""np"""    )[input_name]
            __snake_case			:Dict          =						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 					__lowercase						(							self    ) ->      List[str]:






            '''simple docstring'''





            __snake_case			:Dict          =						self.feat_extract_dict
            __snake_case			:Union[str, Any]          =						True
            __snake_case			:Tuple          =						self.feature_extraction_class(**a__    )
            __snake_case			:str          =						self.feat_extract_tester.prepare_inputs_for_target()
            __snake_case			:Optional[Any]          =						[len(a__    ) for x in speech_inputs]
            __snake_case			:Union[str, Any]          =						feat_extract.model_input_names[0]

            __snake_case			:Optional[Any]          =						BatchFeature({input_name: speech_inputs}    )

            __snake_case			:Dict          =						feat_extract.num_mel_bins  # hack!

            __snake_case			:Optional[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 					__lowercase						(							self    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:Union[str, Any]          =						self.feat_extract_dict
            __snake_case			:int          =						True
            __snake_case			:Union[str, Any]          =						self.feature_extraction_class(**a__    )
            __snake_case			:List[Any]          =						self.feat_extract_tester.prepare_inputs_for_target()
            __snake_case			:str          =						[len(a__    ) for x in speech_inputs]
            __snake_case			:List[Any]          =						feat_extract.model_input_names[0]

            __snake_case			:Optional[Any]          =						BatchFeature({input_name: speech_inputs}    )
            __snake_case			:Optional[int]          =						min(a__    )

            __snake_case			:Union[str, Any]          =						feat_extract.num_mel_bins  # hack!

            __snake_case			:List[Any]          =						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 					__lowercase						(							self			,						a__    ) ->      int:






            '''simple docstring'''





            from datasets import load_dataset

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

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



       def 					__lowercase						(							self    ) ->      Dict:






            '''simple docstring'''





            __snake_case			:Dict          =						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

            __snake_case			:Optional[int]          =						self._load_datasamples(1    )
            __snake_case			:Any          =						SpeechTaFeatureExtractor()
            __snake_case			:List[Any]          =						feature_extractor(a__			,						return_tensors="""pt"""    ).input_values
            self.assertEquals(input_values.shape			,						(1, 9_36_80)    )
            self.assertTrue(torch.allclose(input_values[0, :30]			,						a__			,						atol=1e-6    )    )



       def 					__lowercase						(							self    ) ->      List[Any]:






            '''simple docstring'''





            __snake_case			:str          =						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			:Optional[int]          =						self._load_datasamples(1    )
            __snake_case			:Any          =						SpeechTaFeatureExtractor()
            __snake_case			:List[str]          =						feature_extractor(audio_target=a__			,						return_tensors="""pt"""    ).input_values
            self.assertEquals(input_values.shape			,						(1, 3_66, 80)    )
            self.assertTrue(torch.allclose(input_values[0, 0, :30]			,						a__			,						atol=1e-4    )    )










from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


lowerCamelCase__							=     {
    """configuration_canine""": ["""CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CanineConfig"""],
    """tokenization_canine""": ["""CanineTokenizer"""],
}

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowerCamelCase__							=     [
         """CANINE_PRETRAINED_MODEL_ARCHIVE_LIST""",
         """CanineForMultipleChoice""",
         """CanineForQuestionAnswering""",
         """CanineForSequenceClassification""",
         """CanineForTokenClassification""",
         """CanineLayer""",
         """CanineModel""",
         """CaninePreTrainedModel""",
         """load_tf_weights_in_canine""",
     ]


if TYPE_CHECKING:
     from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
     from .tokenization_canine import CanineTokenizer

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_canine import (
              CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
              CanineForMultipleChoice,
              CanineForQuestionAnswering,
              CanineForSequenceClassification,
              CanineForTokenClassification,
              CanineLayer,
              CanineModel,
              CaninePreTrainedModel,
              load_tf_weights_in_canine,
          )


else:
     import sys

     lowerCamelCase__							=     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


