



"""simple docstring"""
import unittest

from transformers import TrOCRConfig
from transformers.testing_utils import is_torch_available, require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM


@require_torch
class 							lowerCamelCase_:





     '''simple docstring'''



     def __init__(    self				,       lowerCamelCase__				,       lowerCamelCase__=9_9				,       lowerCamelCase__=1_3				,       lowerCamelCase__=1_6				,       lowerCamelCase__=7				,       lowerCamelCase__=True				,       lowerCamelCase__=True				,       lowerCamelCase__=True				,       lowerCamelCase__=False				,       lowerCamelCase__=True				,       lowerCamelCase__=2				,       lowerCamelCase__=3_2				,       lowerCamelCase__=4				,       lowerCamelCase__=4				,       lowerCamelCase__=3_0				,       lowerCamelCase__=0				,       lowerCamelCase__=1				,       lowerCamelCase__=2				,       lowerCamelCase__=None				,       ):
         _lowerCamelCase        =				parent
         _lowerCamelCase        =				batch_size
         _lowerCamelCase        =				decoder_seq_length
         # For common tests
         _lowerCamelCase        =				self.decoder_seq_length
         _lowerCamelCase        =				is_training
         _lowerCamelCase        =				use_attention_mask
         _lowerCamelCase        =				use_labels

         _lowerCamelCase        =				vocab_size
         _lowerCamelCase        =				d_model
         _lowerCamelCase        =				d_model
         _lowerCamelCase        =				decoder_layers
         _lowerCamelCase        =				decoder_layers
         _lowerCamelCase        =				decoder_ffn_dim
         _lowerCamelCase        =				decoder_attention_heads
         _lowerCamelCase        =				decoder_attention_heads
         _lowerCamelCase        =				eos_token_id
         _lowerCamelCase        =				bos_token_id
         _lowerCamelCase        =				pad_token_id
         _lowerCamelCase        =				decoder_start_token_id
         _lowerCamelCase        =				use_cache
         _lowerCamelCase        =				max_position_embeddings

         _lowerCamelCase        =				None
         _lowerCamelCase        =				decoder_seq_length
         _lowerCamelCase        =				2
         _lowerCamelCase        =				1

     def 			snake_case__      (    self   ):
         _lowerCamelCase        =				ids_tensor([self.batch_size, self.decoder_seq_length]				,       self.vocab_size   )

         _lowerCamelCase        =				None
         if self.use_attention_mask:
             _lowerCamelCase        =				ids_tensor([self.batch_size, self.decoder_seq_length]				,       vocab_size=2   )

         _lowerCamelCase        =				None
         if self.use_labels:
             _lowerCamelCase        =				ids_tensor([self.batch_size, self.decoder_seq_length]				,       self.vocab_size   )

         _lowerCamelCase        =				TrOCRConfig(
             vocab_size=self.vocab_size				,       d_model=self.d_model				,       decoder_layers=self.decoder_layers				,       decoder_ffn_dim=self.decoder_ffn_dim				,       decoder_attention_heads=self.decoder_attention_heads				,       eos_token_id=self.eos_token_id				,       bos_token_id=self.bos_token_id				,       use_cache=self.use_cache				,       pad_token_id=self.pad_token_id				,       decoder_start_token_id=self.decoder_start_token_id				,       max_position_embeddings=self.max_position_embeddings				,       )

         return (config, input_ids, attention_mask, lm_labels)

     def 			snake_case__      (    self				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       lowerCamelCase__				,       ):
         _lowerCamelCase        =				True
         _lowerCamelCase        =				TrOCRDecoder(config=lowerCamelCase__   ).to(lowerCamelCase__   ).eval()
         _lowerCamelCase        =				input_ids[:2]

         input_ids[input_ids == 0] += 1
         # first forward pass
         _lowerCamelCase        =				model(lowerCamelCase__				,       use_cache=lowerCamelCase__   )
         _lowerCamelCase        =				model(lowerCamelCase__   )
         _lowerCamelCase        =				model(lowerCamelCase__				,       use_cache=lowerCamelCase__   )

         self.parent.assertTrue(len(lowerCamelCase__   ) == len(lowerCamelCase__   )   )
         self.parent.assertTrue(len(lowerCamelCase__   ) == len(lowerCamelCase__   ) + 1   )

         _lowerCamelCase        =				outputs['''past_key_values''']

         # create hypothetical next token and extent to next_input_ids
         _lowerCamelCase        =				ids_tensor((2, 1)				,       config.vocab_size - 1   ) + 1

         # append to next input_ids and
         _lowerCamelCase        =				torch.cat([input_ids, next_tokens]				,       dim=-1   )

         _lowerCamelCase        =				model(lowerCamelCase__   )['''last_hidden_state''']
         _lowerCamelCase        =				model(lowerCamelCase__				,       past_key_values=lowerCamelCase__   )['''last_hidden_state''']

         # select random slice
         _lowerCamelCase        =				ids_tensor((1,)				,       output_from_past.shape[-1]   ).item()
         _lowerCamelCase        =				output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
         _lowerCamelCase        =				output_from_past[:, 0, random_slice_idx].detach()

         # test that outputs are equal for slice
         assert torch.allclose(lowerCamelCase__				,       lowerCamelCase__				,       atol=1e-3   )





     def 			snake_case__      (    self   ):
         _lowerCamelCase        =				self.prepare_config_and_inputs()
         _lowerCamelCase  ,     _lowerCamelCase  ,     _lowerCamelCase  ,     _lowerCamelCase        =				config_and_inputs

         _lowerCamelCase        =				{'''input_ids''': input_ids, '''attention_mask''': attention_mask}
         return config, inputs_dict


@require_torch
class 							lowerCamelCase_(   A__,				A__,				A__,				unittest.TestCase    ):





     '''simple docstring'''



     lowercase__   :       int										= (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else ()
     lowercase__   :       List[str]										= (TrOCRForCausalLM,) if is_torch_available() else ()
     lowercase__   :       Tuple										= {'text-generation': TrOCRForCausalLM} if is_torch_available() else {}
     lowercase__   :       Dict										= True
     lowercase__   :       Optional[Any]										= False

     def 			snake_case__      (    self   ):
         _lowerCamelCase        =				TrOCRStandaloneDecoderModelTester(self				,       is_training=lowerCamelCase__   )
         _lowerCamelCase        =				ConfigTester(self				,       config_class=lowerCamelCase__   )

     def 			snake_case__      (    self   ):
         pass

     def 			snake_case__      (    self   ):
         pass

     def 			snake_case__      (    self   ):
         pass

     def 			snake_case__      (    self   ):
         self.config_tester.run_common_tests()

     def 			snake_case__      (    self   ):
         _lowerCamelCase        =				self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_decoder_model_past(*lowerCamelCase__   )

     def 			snake_case__      (    self   ):
         return





     @unittest.skip('''The model doesn\'t support left padding'''   )  # and it's not used enough to be worth fixing :)
     def 			snake_case__      (    self   ):
         pass





"""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

__SCREAMING_SNAKE_CASE  :						Dict    							=      random.Random()



def        lowerCAmelCase_(   lowercase_     :							Dict						,   lowercase_     :							int=1.0						,   lowercase_     :							str=None						,   lowercase_     :							Optional[int]=None							)	->       Any:
				if rng is None:
								_lowerCamelCase        =				global_rng

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





					'''simple docstring'''



					def __init__(    self				,       lowerCamelCase__				,       lowerCamelCase__=7				,       lowerCamelCase__=4_0_0				,       lowerCamelCase__=2_0_0_0				,       lowerCamelCase__=1_0				,       lowerCamelCase__=1_6_0				,       lowerCamelCase__=8				,       lowerCamelCase__=0.0				,       lowerCamelCase__=4_0_0_0				,       lowerCamelCase__=False				,       lowerCamelCase__=True				,       ):
									_lowerCamelCase        =				parent
									_lowerCamelCase        =				batch_size
									_lowerCamelCase        =				min_seq_length
									_lowerCamelCase        =				max_seq_length
									_lowerCamelCase        =				(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
									_lowerCamelCase        =				padding_value
									_lowerCamelCase        =				sampling_rate
									_lowerCamelCase        =				return_attention_mask
									_lowerCamelCase        =				do_normalize
									_lowerCamelCase        =				feature_size
									_lowerCamelCase        =				chunk_length
									_lowerCamelCase        =				hop_length

					def 			snake_case__      (    self   ):
									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 			snake_case__      (    self				,       lowerCamelCase__=False				,       lowerCamelCase__=False   ):
									def _flatten(lowerCamelCase__   ):
													return list(itertools.chain(*lowerCamelCase__   )   )

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


@require_torch
@require_torchaudio
class 							lowerCamelCase_(   A__,				unittest.TestCase    ):





					'''simple docstring'''



					lowercase__   :       Optional[int]										= WhisperFeatureExtractor if is_speech_available() else None

					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				WhisperFeatureExtractionTester(self   )

					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_dict   )

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

									_lowerCamelCase        =				feat_extract_first.to_dict()
									_lowerCamelCase        =				feat_extract_second.to_dict()
									_lowerCamelCase        =				feat_extract_first.mel_filters
									_lowerCamelCase        =				feat_extract_second.mel_filters
									self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__   )   )
									self.assertEqual(lowerCamelCase__				,       lowerCamelCase__   )

					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_dict   )

									with tempfile.TemporaryDirectory() as tmpdirname:
													_lowerCamelCase        =				os.path.join(lowerCamelCase__				,       '''feat_extract.json'''   )
													feat_extract_first.to_json_file(lowerCamelCase__   )
													_lowerCamelCase        =				self.feature_extraction_class.from_json_file(lowerCamelCase__   )

									_lowerCamelCase        =				feat_extract_first.to_dict()
									_lowerCamelCase        =				feat_extract_second.to_dict()
									_lowerCamelCase        =				feat_extract_first.mel_filters
									_lowerCamelCase        =				feat_extract_second.mel_filters
									self.assertTrue(np.allclose(lowerCamelCase__				,       lowerCamelCase__   )   )
									self.assertEqual(lowerCamelCase__				,       lowerCamelCase__   )

					def 			snake_case__      (    self   ):
									# Tests that all call wrap to encode_plus and batch_encode_plus
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
									# create three inputs of length 800, 1000, and 1200
									_lowerCamelCase        =				[floats_list((1, x)   )[0] for x in range(8_0_0				,       1_4_0_0				,       2_0_0   )]
									_lowerCamelCase        =				[np.asarray(lowerCamelCase__   ) for speech_input in speech_inputs]

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

									# Test batched
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				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.
									_lowerCamelCase        =				[floats_list((1, x)   )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
									_lowerCamelCase        =				np.asarray(lowerCamelCase__   )
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				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
									_lowerCamelCase        =				[floats_list((1, x)   )[0] for x in range(2_0_0				,       (feature_extractor.n_samples + 5_0_0)				,       2_0_0   )]
									_lowerCamelCase        =				[np.asarray(lowerCamelCase__   ) for speech_input in speech_inputs]

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

									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''np'''   ).input_features
									_lowerCamelCase        =				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 			snake_case__      (    self   ):
									import torch

									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
									_lowerCamelCase        =				np.random.rand(1_0_0				,       3_2   ).astype(np.floataa   )
									_lowerCamelCase        =				np_speech_inputs.tolist()

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

					def 			snake_case__      (    self				,       lowerCamelCase__   ):
									_lowerCamelCase        =				load_dataset('''hf-internal-testing/librispeech_asr_dummy'''				,       '''clean'''				,       split='''validation'''   )
									# automatic decoding with librispeech
									_lowerCamelCase        =				ds.sort('''id'''   ).select(range(lowerCamelCase__   )   )[:num_samples]['''audio''']

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

					def 			snake_case__      (    self   ):
									# fmt: off
									_lowerCamelCase        =				torch.tensor(
									    [
									        0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
									        0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
									        0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
									        -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
									    ]   )
									# fmt: on

									_lowerCamelCase        =				self._load_datasamples(1   )
									_lowerCamelCase        =				WhisperFeatureExtractor()
									_lowerCamelCase        =				feature_extractor(lowerCamelCase__				,       return_tensors='''pt'''   ).input_features
									self.assertEqual(input_features.shape				,       (1, 8_0, 3_0_0_0)   )
									self.assertTrue(torch.allclose(input_features[0, 0, :3_0]				,       lowerCamelCase__				,       atol=1e-4   )   )





					def 			snake_case__      (    self   ):
									_lowerCamelCase        =				self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
									_lowerCamelCase        =				self._load_datasamples(1   )[0]
									_lowerCamelCase        =				((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5  # Rescale to [0, 65535] to show issue
									_lowerCamelCase        =				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   )   )
