





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_tf_available,
    is_torch_available,
)


__A				:    Union[str, Any]       =   {
    "configuration_speech_to_text": ["SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP", "Speech2TextConfig"],
    "processing_speech_to_text": ["Speech2TextProcessor"],
}

try:
				if not is_sentencepiece_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				__A				:    List[Any]       =   ["Speech2TextTokenizer"]

try:
				if not is_speech_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				__A				:    List[Any]       =   ["Speech2TextFeatureExtractor"]

try:
				if not is_tf_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				__A				:    int       =   [
				    "TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST",
				    "TFSpeech2TextForConditionalGeneration",
				    "TFSpeech2TextModel",
				    "TFSpeech2TextPreTrainedModel",
				]

try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				__A				:    Tuple       =   [
				    "SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST",
				    "Speech2TextForConditionalGeneration",
				    "Speech2TextModel",
				    "Speech2TextPreTrainedModel",
				]


if TYPE_CHECKING:
				from .configuration_speech_to_text import SPEECH_TO_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextConfig
				from .processing_speech_to_text import SpeechaTextProcessor

				try:
								if not is_sentencepiece_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .tokenization_speech_to_text import SpeechaTextTokenizer

				try:
								if not is_speech_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .feature_extraction_speech_to_text import SpeechaTextFeatureExtractor

				try:
								if not is_tf_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_tf_speech_to_text import (
								    TF_SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
								    TFSpeechaTextForConditionalGeneration,
								    TFSpeechaTextModel,
								    TFSpeechaTextPreTrainedModel,
								)

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_speech_to_text import (
								    SPEECH_TO_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
								    SpeechaTextForConditionalGeneration,
								    SpeechaTextModel,
								    SpeechaTextPreTrainedModel,
								)

else:
				import sys

				__A				:    Dict       =   _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)










from __future__ import annotations

import unittest

from transformers import AutoTokenizer, MBartConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
				import tensorflow as tf

				from transformers import TFAutoModelForSeqaSeqLM, TFMBartForConditionalGeneration, TFMBartModel

@require_tf
class 	A_       :
	UpperCAmelCase__					=			MBartConfig
	UpperCAmelCase__					=			{}
	UpperCAmelCase__					=			'''gelu'''
	def __init__(    self							,					_A							,					_A=1_3							,					_A=7							,					_A=True							,					_A=False							,					_A=9_9							,					_A=3_2							,					_A=2							,					_A=4							,					_A=3_7							,					_A=0.1							,					_A=0.1							,					_A=2_0							,					_A=2							,					_A=1							,					_A=0							,					):






				'''simple docstring'''







				UpperCAmelCase   		=				parent
				UpperCAmelCase   		=				batch_size
				UpperCAmelCase   		=				seq_length
				UpperCAmelCase   		=				is_training
				UpperCAmelCase   		=				use_labels
				UpperCAmelCase   		=				vocab_size
				UpperCAmelCase   		=				hidden_size
				UpperCAmelCase   		=				num_hidden_layers
				UpperCAmelCase   		=				num_attention_heads
				UpperCAmelCase   		=				intermediate_size
				UpperCAmelCase   		=				hidden_dropout_prob
				UpperCAmelCase   		=				attention_probs_dropout_prob
				UpperCAmelCase   		=				max_position_embeddings
				UpperCAmelCase   		=				eos_token_id
				UpperCAmelCase   		=				pad_token_id
				UpperCAmelCase   		=				bos_token_id
	def      _lowercase				(    self		):






				'''simple docstring'''







				UpperCAmelCase   		=				ids_tensor([self.batch_size, self.seq_length - 1]							,					self.vocab_size		)
				UpperCAmelCase   		=				tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size		)							,					1		)
				UpperCAmelCase   		=				tf.concat([input_ids, eos_tensor]							,					axis=1		)

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

				UpperCAmelCase   		=				self.config_cls(
				    vocab_size=self.vocab_size							,					d_model=self.hidden_size							,					encoder_layers=self.num_hidden_layers							,					decoder_layers=self.num_hidden_layers							,					encoder_attention_heads=self.num_attention_heads							,					decoder_attention_heads=self.num_attention_heads							,					encoder_ffn_dim=self.intermediate_size							,					decoder_ffn_dim=self.intermediate_size							,					dropout=self.hidden_dropout_prob							,					attention_dropout=self.attention_probs_dropout_prob							,					max_position_embeddings=self.max_position_embeddings							,					eos_token_ids=[2]							,					bos_token_id=self.bos_token_id							,					pad_token_id=self.pad_token_id							,					decoder_start_token_id=self.pad_token_id							,					**self.config_updates							,					)
				UpperCAmelCase   		=				prepare_mbart_inputs_dict(_A							,					_A							,					_A		)
				return config, inputs_dict







	def      _lowercase				(    self							,					_A							,					_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				TFMBartModel(config=_A		).get_decoder()
				UpperCAmelCase   		=				inputs_dict['''input_ids''']

				UpperCAmelCase   		=				input_ids[:1, :]
				UpperCAmelCase   		=				inputs_dict['''attention_mask'''][:1, :]
				UpperCAmelCase   		=				inputs_dict['''head_mask''']
				UpperCAmelCase   		=				1

				# first forward pass
				UpperCAmelCase   		=				model(_A							,					attention_mask=_A							,					head_mask=_A							,					use_cache=_A		)

				UpperCAmelCase		,			UpperCAmelCase   		=				outputs.to_tuple()
				UpperCAmelCase   		=				past_key_values[1]





def 						__SCREAMING_SNAKE_CASE  (				UpperCamelCase__			,			UpperCamelCase__			,			UpperCamelCase__			,			UpperCamelCase__=None			,			UpperCamelCase__=None			,			UpperCamelCase__=None			,			UpperCamelCase__=None			,			UpperCamelCase__=None			,			)  ->				List[str]:







			'''simple docstring'''

			if attention_mask is None:
						UpperCAmelCase   		=				tf.cast(tf.math.not_equal(UpperCamelCase__			,			config.pad_token_id )			,			tf.inta )
			if decoder_attention_mask is None:
						UpperCAmelCase   		=				tf.concat(
						    [
						        tf.ones(decoder_input_ids[:, :1].shape			,			dtype=tf.inta ),
						        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]			,			config.pad_token_id )			,			tf.inta ),
						    ]			,			axis=-1			,			)
			if head_mask is None:
						UpperCAmelCase   		=				tf.ones((config.encoder_layers, config.encoder_attention_heads) )
			if decoder_head_mask is None:
						UpperCAmelCase   		=				tf.ones((config.decoder_layers, config.decoder_attention_heads) )
			if cross_attn_head_mask is None:
						UpperCAmelCase   		=				tf.ones((config.decoder_layers, config.decoder_attention_heads) )
			return {
			    "input_ids": input_ids,
			    "decoder_input_ids": decoder_input_ids,
			    "attention_mask": attention_mask,
			    "decoder_attention_mask": decoder_attention_mask,
			    "head_mask": head_mask,
			    "decoder_head_mask": decoder_head_mask,
			    "cross_attn_head_mask": cross_attn_head_mask,
			}

@require_tf
class 	A_       (a_     ,							a_     ,							unittest.TestCase			):
	UpperCAmelCase__					=			(TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
	UpperCAmelCase__					=			(TFMBartForConditionalGeneration,) if is_tf_available() else ()
	UpperCAmelCase__					=			(
	    {
	        '''conversational''': TFMBartForConditionalGeneration,
	        '''feature-extraction''': TFMBartModel,
	        '''summarization''': TFMBartForConditionalGeneration,
	        '''text2text-generation''': TFMBartForConditionalGeneration,
	        '''translation''': TFMBartForConditionalGeneration,
	    }
	    if is_tf_available()
	    else {}
	)
	UpperCAmelCase__					=			True
	UpperCAmelCase__					=			False
	UpperCAmelCase__					=			False
	def      _lowercase				(    self							,					_A							,					_A							,					_A							,					_A							,					_A		):






				'''simple docstring'''







				if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
							# Exception encountered when calling layer '...'
							return True

				return False
	def      _lowercase				(    self		):






				'''simple docstring'''







				UpperCAmelCase   		=				TFMBartModelTester(self		)
				UpperCAmelCase   		=				ConfigTester(self							,					config_class=_A		)
	def      _lowercase				(    self		):






				'''simple docstring'''







				self.config_tester.run_common_tests()







	def      _lowercase				(    self		):






				'''simple docstring'''







				UpperCAmelCase   		=				self.model_tester.prepare_config_and_inputs_for_common()
				self.model_tester.check_decoder_model_past_large_inputs(*_A		)

@require_sentencepiece
@require_tokenizers
@require_tf
class 	A_       (unittest.TestCase			):
	UpperCAmelCase__					=			[
	    ''' UN Chief Says There Is No Military Solution in Syria''',
	]
	UpperCAmelCase__					=			[
	    '''Şeful ONU declară că nu există o soluţie militară în Siria''',
	]
	UpperCAmelCase__					=			'''facebook/mbart-large-en-ro'''
	@cached_property
	def      _lowercase				(    self		):






				'''simple docstring'''







				return AutoTokenizer.from_pretrained(self.model_name		)
	@cached_property
	def      _lowercase				(    self		):






				'''simple docstring'''







				UpperCAmelCase   		=				TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name		)
				return model
	def      _lowercase				(    self							,					**_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				self.translate_src_text(**_A		)
				self.assertListEqual(self.expected_text							,					_A		)
	def      _lowercase				(    self							,					**_A		):






				'''simple docstring'''







				UpperCAmelCase   		=				self.tokenizer(self.src_text							,					**_A							,					return_tensors='''tf'''		)
				UpperCAmelCase   		=				self.model.generate(
				    model_inputs.input_ids							,					attention_mask=model_inputs.attention_mask							,					num_beams=2		)
				UpperCAmelCase   		=				self.tokenizer.batch_decode(_A							,					skip_special_tokens=_A		)
				return generated_words







	@slow
	def      _lowercase				(    self		):






				'''simple docstring'''







				self._assert_generated_batch_equal_expected()



