"""simple docstring"""






import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
       from transformers import WhisperFeatureExtractor

if is_torch_available():
       import torch

__lowerCAmelCase					: Dict        =random.Random()


def     UpperCAmelCase__ (       lowerCAmelCase__  :Optional[Any]      ,	lowerCAmelCase__  :List[str]=1.0      ,	lowerCAmelCase__  :Tuple=None      ,	lowerCAmelCase__  :Any=None	)				->					Dict:
      '''simple docstring'''


      if rng is None:
            lowercase														=			global_rng

      lowercase														=			[]
      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 				_A		( unittest.TestCase			):

      def __init__(		self	, __lowerCAmelCase	, __lowerCAmelCase=7	, __lowerCAmelCase=400	, __lowerCAmelCase=2000	, __lowerCAmelCase=10	, __lowerCAmelCase=160	, __lowerCAmelCase=8	, __lowerCAmelCase=0.0	, __lowerCAmelCase=4000	, __lowerCAmelCase=False	, __lowerCAmelCase=True	, ):







            """simple docstring"""



            lowercase														=			parent
            lowercase														=			batch_size
            lowercase														=			min_seq_length
            lowercase														=			max_seq_length
            lowercase														=			(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
            lowercase														=			padding_value
            lowercase														=			sampling_rate
            lowercase														=			return_attention_mask
            lowercase														=			do_normalize
            lowercase														=			feature_size
            lowercase														=			chunk_length
            lowercase														=			hop_length

      def        A__ (		self		):







            """simple docstring"""



            return {
                "feature_size": self.feature_size,
                "hop_length": self.hop_length,
                "chunk_length": self.chunk_length,
                "padding_value": self.padding_value,
                "sampling_rate": self.sampling_rate,
                "return_attention_mask": self.return_attention_mask,
                "do_normalize": self.do_normalize,
            }







      def        A__ (		self	, __lowerCAmelCase=False	, __lowerCAmelCase=False		):







            """simple docstring"""



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

            if equal_length:
                  lowercase														=			[floats_list((self.max_seq_length, self.feature_size)		) for _ in range(self.batch_size		)]
            else:
                  # make sure that inputs increase in size
                  lowercase														=			[
                      floats_list((x, self.feature_size)		)
                      for x in range(self.min_seq_length	, self.max_seq_length	, self.seq_length_diff		)
                  ]
            if numpify:
                  lowercase														=			[np.asarray(__lowerCAmelCase		) for x in speech_inputs]
            return speech_inputs






@require_torch
@require_torchaudio
class 				_A		( lowerCAmelCase						,					unittest.TestCase			):
      snake_case__    :     Optional[Any]													=			WhisperFeatureExtractor if is_speech_available() else None

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			WhisperFeatureExtractionTester(self		)

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			self.feature_extraction_class(**self.feat_extract_dict		)

            with tempfile.TemporaryDirectory() as tmpdirname:
                  lowercase														=			feat_extract_first.save_pretrained(__lowerCAmelCase		)[0]
                  check_json_file_has_correct_format(__lowerCAmelCase		)
                  lowercase														=			self.feature_extraction_class.from_pretrained(__lowerCAmelCase		)

            lowercase														=			feat_extract_first.to_dict()
            lowercase														=			feat_extract_second.to_dict()
            lowercase														=			feat_extract_first.mel_filters
            lowercase														=			feat_extract_second.mel_filters
            self.assertTrue(np.allclose(__lowerCAmelCase	, __lowerCAmelCase		)		)
            self.assertEqual(__lowerCAmelCase	, __lowerCAmelCase		)

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			self.feature_extraction_class(**self.feat_extract_dict		)

            with tempfile.TemporaryDirectory() as tmpdirname:
                  lowercase														=			os.path.join(__lowerCAmelCase	, """feat_extract.json"""		)
                  feat_extract_first.to_json_file(__lowerCAmelCase		)
                  lowercase														=			self.feature_extraction_class.from_json_file(__lowerCAmelCase		)

            lowercase														=			feat_extract_first.to_dict()
            lowercase														=			feat_extract_second.to_dict()
            lowercase														=			feat_extract_first.mel_filters
            lowercase														=			feat_extract_second.mel_filters
            self.assertTrue(np.allclose(__lowerCAmelCase	, __lowerCAmelCase		)		)
            self.assertEqual(__lowerCAmelCase	, __lowerCAmelCase		)

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
            # create three inputs of length 800, 1000, and 1200
            lowercase														=			[floats_list((1, x)		)[0] for x in range(800	, 1400	, 200		)]
            lowercase														=			[np.asarray(__lowerCAmelCase		) for speech_input in speech_inputs]

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

            # Test batched
            lowercase														=			feature_extractor(__lowerCAmelCase	, return_tensors="""np"""		).input_features
            lowercase														=			feature_extractor(__lowerCAmelCase	, return_tensors="""np"""		).input_features
            for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase	, __lowerCAmelCase		):
                  self.assertTrue(np.allclose(__lowerCAmelCase	, __lowerCAmelCase	, atol=1E-3		)		)

            # Test 2-D numpy arrays are batched.
            lowercase														=			[floats_list((1, x)		)[0] for x in (800, 800, 800)]
            lowercase														=			np.asarray(__lowerCAmelCase		)
            lowercase														=			feature_extractor(__lowerCAmelCase	, return_tensors="""np"""		).input_features
            lowercase														=			feature_extractor(__lowerCAmelCase	, return_tensors="""np"""		).input_features
            for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase	, __lowerCAmelCase		):
                  self.assertTrue(np.allclose(__lowerCAmelCase	, __lowerCAmelCase	, atol=1E-3		)		)

            # Test truncation required
            lowercase														=			[floats_list((1, x)		)[0] for x in range(200	, (feature_extractor.n_samples + 500)	, 200		)]
            lowercase														=			[np.asarray(__lowerCAmelCase		) for speech_input in speech_inputs]

            lowercase														=			[x[: feature_extractor.n_samples] for x in speech_inputs]
            lowercase														=			[np.asarray(__lowerCAmelCase		) for speech_input in speech_inputs_truncated]

            lowercase														=			feature_extractor(__lowerCAmelCase	, return_tensors="""np"""		).input_features
            lowercase														=			feature_extractor(__lowerCAmelCase	, return_tensors="""np"""		).input_features
            for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase	, __lowerCAmelCase		):
                  self.assertTrue(np.allclose(__lowerCAmelCase	, __lowerCAmelCase	, atol=1E-3		)		)

      def        A__ (		self		):







            """simple docstring"""



            import torch

            lowercase														=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
            lowercase														=			np.random.rand(100	, 32		).astype(np.floataa		)
            lowercase														=			np_speech_inputs.tolist()

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

      def        A__ (		self	, __lowerCAmelCase		):







            """simple docstring"""



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

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

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			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

            lowercase														=			self._load_datasamples(1		)
            lowercase														=			WhisperFeatureExtractor()
            lowercase														=			feature_extractor(__lowerCAmelCase	, return_tensors="""pt"""		).input_features
            self.assertEqual(input_features.shape	, (1, 80, 3000)		)
            self.assertTrue(torch.allclose(input_features[0, 0, :30]	, __lowerCAmelCase	, atol=1E-4		)		)







      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
            lowercase														=			self._load_datasamples(1		)[0]
            lowercase														=			((audio - audio.min()) / (audio.max() - audio.min())) * 6_5535  # Rescale to [0, 65535] to show issue
            lowercase														=			feat_extract.zero_mean_unit_var_norm([audio]	, attention_mask=__lowerCAmelCase		)[0]

            self.assertTrue(np.all(np.mean(__lowerCAmelCase		) < 1E-3		)		)
            self.assertTrue(np.all(np.abs(np.var(__lowerCAmelCase		) - 1		) < 1E-3		)		)




"""simple docstring"""






import unittest

import numpy as np

from transformers import RobertaConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
       from transformers.models.roberta.modeling_flax_roberta import (
           FlaxRobertaForCausalLM,
           FlaxRobertaForMaskedLM,
           FlaxRobertaForMultipleChoice,
           FlaxRobertaForQuestionAnswering,
           FlaxRobertaForSequenceClassification,
           FlaxRobertaForTokenClassification,
           FlaxRobertaModel,
       )





class 				_A		( unittest.TestCase			):

      def __init__(		self	, __lowerCAmelCase	, __lowerCAmelCase=13	, __lowerCAmelCase=7	, __lowerCAmelCase=True	, __lowerCAmelCase=True	, __lowerCAmelCase=True	, __lowerCAmelCase=True	, __lowerCAmelCase=99	, __lowerCAmelCase=32	, __lowerCAmelCase=5	, __lowerCAmelCase=4	, __lowerCAmelCase=37	, __lowerCAmelCase="gelu"	, __lowerCAmelCase=0.1	, __lowerCAmelCase=0.1	, __lowerCAmelCase=512	, __lowerCAmelCase=16	, __lowerCAmelCase=2	, __lowerCAmelCase=0.0_2	, __lowerCAmelCase=4	, ):







            """simple docstring"""



            lowercase														=			parent
            lowercase														=			batch_size
            lowercase														=			seq_length
            lowercase														=			is_training
            lowercase														=			use_attention_mask
            lowercase														=			use_token_type_ids
            lowercase														=			use_labels
            lowercase														=			vocab_size
            lowercase														=			hidden_size
            lowercase														=			num_hidden_layers
            lowercase														=			num_attention_heads
            lowercase														=			intermediate_size
            lowercase														=			hidden_act
            lowercase														=			hidden_dropout_prob
            lowercase														=			attention_probs_dropout_prob
            lowercase														=			max_position_embeddings
            lowercase														=			type_vocab_size
            lowercase														=			type_sequence_label_size
            lowercase														=			initializer_range
            lowercase														=			num_choices

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			ids_tensor([self.batch_size, self.seq_length]	, self.vocab_size		)

            lowercase														=			None
            if self.use_attention_mask:
                  lowercase														=			random_attention_mask([self.batch_size, self.seq_length]		)

            lowercase														=			None
            if self.use_token_type_ids:
                  lowercase														=			ids_tensor([self.batch_size, self.seq_length]	, self.type_vocab_size		)

            lowercase														=			RobertaConfig(
                vocab_size=self.vocab_size	, hidden_size=self.hidden_size	, num_hidden_layers=self.num_hidden_layers	, num_attention_heads=self.num_attention_heads	, intermediate_size=self.intermediate_size	, hidden_act=self.hidden_act	, hidden_dropout_prob=self.hidden_dropout_prob	, attention_probs_dropout_prob=self.attention_probs_dropout_prob	, max_position_embeddings=self.max_position_embeddings	, type_vocab_size=self.type_vocab_size	, is_decoder=__lowerCAmelCase	, initializer_range=self.initializer_range	, )

            return config, input_ids, token_type_ids, attention_mask

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			self.prepare_config_and_inputs()
            lowercase							,							lowercase							,							lowercase							,							lowercase														=			config_and_inputs
            lowercase														=			{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask}
            return config, inputs_dict







      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			self.prepare_config_and_inputs()
            lowercase							,							lowercase							,							lowercase							,							lowercase														=			config_and_inputs

            lowercase														=			True
            lowercase														=			floats_tensor([self.batch_size, self.seq_length, self.hidden_size]		)
            lowercase														=			ids_tensor([self.batch_size, self.seq_length]	, vocab_size=2		)

            return (
                config,
                input_ids,
                token_type_ids,
                encoder_hidden_states,
                encoder_attention_mask,
            )






@require_flax
class 				_A		( lowerCAmelCase						,					unittest.TestCase			):
      snake_case__    :     Optional[int]													=			True

      snake_case__    :     List[str]													=			(
          (
              FlaxRobertaModel,
              FlaxRobertaForCausalLM,
              FlaxRobertaForMaskedLM,
              FlaxRobertaForSequenceClassification,
              FlaxRobertaForTokenClassification,
              FlaxRobertaForMultipleChoice,
              FlaxRobertaForQuestionAnswering,
          )
          if is_flax_available()
          else ()
      )

      def        A__ (		self		):







            """simple docstring"""



            lowercase														=			FlaxRobertaModelTester(self		)







      @slow
      def        A__ (		self		):







            """simple docstring"""



            for model_class_name in self.all_model_classes:
                  lowercase														=			model_class_name.from_pretrained("""roberta-base"""	, from_pt=__lowerCAmelCase		)
                  lowercase														=			model(np.ones((1, 1)		)		)
                  self.assertIsNotNone(__lowerCAmelCase		)



