


import unittest

import pytest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    MBartaaTokenizerFast,
    MBartConfig,
    MBartForConditionalGeneration,
    TranslationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch, slow

from .test_pipelines_common import ANY

@is_pipeline_test
class   A__							(						unittest.TestCase					):






						"""simple docstring"""




						UpperCAmelCase     =  MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
						UpperCAmelCase     =  TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING




						def 							__UpperCamelCase			(    self   : Optional[int]			,      _a   : Union[str, Any]			,      _a   : int			,      _a   : Optional[int]					)							->       Dict:


										"""simple docstring"""





										if isinstance(model.config			,      _a					):
														_SCREAMING_SNAKE_CASE     					=list(tokenizer.lang_code_to_id.keys()					)[:2]
														_SCREAMING_SNAKE_CASE     					=TranslationPipeline(model=_a			,      tokenizer=_a			,      src_lang=_a			,      tgt_lang=_a					)
										else:
														_SCREAMING_SNAKE_CASE     					=TranslationPipeline(model=_a			,      tokenizer=_a					)
										return translator, ["Some string", "Some other text"]




						def 							__UpperCamelCase			(    self   : Any			,      _a   : Any			,      _a   : List[str]					)							->       Optional[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=translator('''Some string'''					)
										self.assertEqual(_a			,      [{'''translation_text''': ANY(_a					)}]					)

										_SCREAMING_SNAKE_CASE     					=translator(['''Some string''']					)
										self.assertEqual(_a			,      [{'''translation_text''': ANY(_a					)}]					)

										_SCREAMING_SNAKE_CASE     					=translator(['''Some string''', '''other string''']					)
										self.assertEqual(_a			,      [{'''translation_text''': ANY(_a					)}, {'''translation_text''': ANY(_a					)}]					)




						@require_torch
						def 							__UpperCamelCase			(    self   : Tuple					)							->       Optional[int]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=pipeline('''translation_en_to_ro'''			,      model='''patrickvonplaten/t5-tiny-random'''			,      framework='''pt'''					)
										_SCREAMING_SNAKE_CASE     					=translator('''This is a test string'''			,      max_length=20					)
										self.assertEqual(
										    _a			,      [
										        {
										            '''translation_text''': (
										                '''Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide'''
										                ''' Beide Beide'''
										            )
										        }
										    ]			,      )




						@require_tf
						def 							__UpperCamelCase			(    self   : List[Any]					)							->       List[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=pipeline('''translation_en_to_ro'''			,      model='''patrickvonplaten/t5-tiny-random'''			,      framework='''tf'''					)
										_SCREAMING_SNAKE_CASE     					=translator('''This is a test string'''			,      max_length=20					)
										self.assertEqual(
										    _a			,      [
										        {
										            '''translation_text''': (
										                '''Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide'''
										                ''' Beide Beide'''
										            )
										        }
										    ]			,      )




						@require_torch
						def 							__UpperCamelCase			(    self   : int					)							->       Any:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=pipeline('''translation_en_to_de'''			,      model='''patrickvonplaten/t5-tiny-random'''			,      framework='''pt'''					)
										_SCREAMING_SNAKE_CASE     					=translator('''This is a test string'''			,      max_length=20					)
										self.assertEqual(
										    _a			,      [
										        {
										            '''translation_text''': (
										                '''monoton monoton monoton monoton monoton monoton monoton monoton monoton monoton urine urine'''
										                ''' urine urine urine urine urine urine urine'''
										            )
										        }
										    ]			,      )




						@require_tf
						def 							__UpperCamelCase			(    self   : Union[str, Any]					)							->       Optional[int]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=pipeline('''translation_en_to_de'''			,      model='''patrickvonplaten/t5-tiny-random'''			,      framework='''tf'''					)
										_SCREAMING_SNAKE_CASE     					=translator('''This is a test string'''			,      max_length=20					)
										self.assertEqual(
										    _a			,      [
										        {
										            '''translation_text''': (
										                '''monoton monoton monoton monoton monoton monoton monoton monoton monoton monoton urine urine'''
										                ''' urine urine urine urine urine urine urine'''
										            )
										        }
										    ]			,      )

class   A__							(						unittest.TestCase					):






						"""simple docstring"""




						@require_torch
						@slow
						def 							__UpperCamelCase			(    self   : str					)							->       List[Any]:


										"""simple docstring"""





										with self.assertRaises(_a					):
														pipeline(task='''translation_cn_to_ar'''					)

										# but we do for this one
										_SCREAMING_SNAKE_CASE     					=pipeline(task='''translation_en_to_de'''					)
										self.assertEqual(translator._preprocess_params['''src_lang''']			,      '''en'''					)
										self.assertEqual(translator._preprocess_params['''tgt_lang''']			,      '''de'''					)




						@require_torch
						@slow
						def 							__UpperCamelCase			(    self   : int					)							->       Optional[int]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=MBartForConditionalGeneration.from_pretrained('''facebook/mbart-large-50-many-to-many-mmt'''					)
										_SCREAMING_SNAKE_CASE     					=MBartaaTokenizerFast.from_pretrained('''facebook/mbart-large-50-many-to-many-mmt'''					)

										_SCREAMING_SNAKE_CASE     					=pipeline(task='''translation'''			,      model=_a			,      tokenizer=_a					)
										# Missing src_lang, tgt_lang
										with self.assertRaises(_a					):
														translator('''This is a test'''					)

										_SCREAMING_SNAKE_CASE     					=translator('''This is a test'''			,      src_lang='''en_XX'''			,      tgt_lang='''ar_AR'''					)
										self.assertEqual(_a			,      [{'''translation_text''': '''هذا إختبار'''}]					)

										_SCREAMING_SNAKE_CASE     					=translator('''This is a test'''			,      src_lang='''en_XX'''			,      tgt_lang='''hi_IN'''					)
										self.assertEqual(_a			,      [{'''translation_text''': '''यह एक परीक्षण है'''}]					)

										# src_lang, tgt_lang can be defined at pipeline call time
										_SCREAMING_SNAKE_CASE     					=pipeline(task='''translation'''			,      model=_a			,      tokenizer=_a			,      src_lang='''en_XX'''			,      tgt_lang='''ar_AR'''					)
										_SCREAMING_SNAKE_CASE     					=translator('''This is a test'''					)
										self.assertEqual(_a			,      [{'''translation_text''': '''هذا إختبار'''}]					)




						@require_torch
						def 							__UpperCamelCase			(    self   : Optional[Any]					)							->       List[str]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					="patrickvonplaten/t5-tiny-random"
										_SCREAMING_SNAKE_CASE     					=pipeline(task='''translation_cn_to_ar'''			,      model=_a					)
										self.assertEqual(translator._preprocess_params['''src_lang''']			,      '''cn'''					)
										self.assertEqual(translator._preprocess_params['''tgt_lang''']			,      '''ar'''					)




						@require_torch
						def 							__UpperCamelCase			(    self   : Optional[int]					)							->       Tuple:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					="patrickvonplaten/t5-tiny-random"
										with pytest.warns(_a			,      match=R'''.*translation_en_to_de.*'''					):
														_SCREAMING_SNAKE_CASE     					=pipeline(task='''translation'''			,      model=_a					)
										self.assertEqual(translator.task			,      '''translation_en_to_de'''					)
										self.assertEqual(translator._preprocess_params['''src_lang''']			,      '''en'''					)
										self.assertEqual(translator._preprocess_params['''tgt_lang''']			,      '''de'''					)




						@require_torch
						def 							__UpperCamelCase			(    self   : Optional[Any]					)							->       Any:


										"""simple docstring"""





										with self.assertRaises(_a					):
														pipeline(task='''translation'''					)



import inspect
import unittest

from transformers import ResNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
							import jax
							import jax.numpy as jnp

							from transformers.models.resnet.modeling_flax_resnet import FlaxResNetForImageClassification, FlaxResNetModel

if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor

class   A__							(						unittest.TestCase					):




						def __init__(    self   : List[Any]			,      _a   : Optional[Any]			,      _a   : int=3			,      _a   : int=32			,      _a   : str=3			,      _a   : List[str]=10			,      _a   : Optional[Any]=[10, 20, 30, 40]			,      _a   : Tuple=[1, 1, 2, 1]			,      _a   : Optional[Any]=True			,      _a   : Optional[int]=True			,      _a   : Any="relu"			,      _a   : Any=3			,      _a   : Tuple=None			,      )							->       Optional[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=parent
										_SCREAMING_SNAKE_CASE     					=batch_size
										_SCREAMING_SNAKE_CASE     					=image_size
										_SCREAMING_SNAKE_CASE     					=num_channels
										_SCREAMING_SNAKE_CASE     					=embeddings_size
										_SCREAMING_SNAKE_CASE     					=hidden_sizes
										_SCREAMING_SNAKE_CASE     					=depths
										_SCREAMING_SNAKE_CASE     					=is_training
										_SCREAMING_SNAKE_CASE     					=use_labels
										_SCREAMING_SNAKE_CASE     					=hidden_act
										_SCREAMING_SNAKE_CASE     					=num_labels
										_SCREAMING_SNAKE_CASE     					=scope
										_SCREAMING_SNAKE_CASE     					=len(_a					)




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


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

										_SCREAMING_SNAKE_CASE     					=self.get_config()

										return config, pixel_values




						def 							__UpperCamelCase			(    self   : List[str]					)							->       Dict:


										"""simple docstring"""





										return ResNetConfig(
										    num_channels=self.num_channels			,      embeddings_size=self.embeddings_size			,      hidden_sizes=self.hidden_sizes			,      depths=self.depths			,      hidden_act=self.hidden_act			,      num_labels=self.num_labels			,      image_size=self.image_size			,      )




						def 							__UpperCamelCase			(    self   : Optional[Any]			,      _a   : Union[str, Any]			,      _a   : List[Any]					)							->       Union[str, Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=FlaxResNetModel(config=_a					)
										_SCREAMING_SNAKE_CASE     					=model(_a					)

										# Output shape (b, c, h, w)
										self.parent.assertEqual(
										    result.last_hidden_state.shape			,      (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)			,      )




						def 							__UpperCamelCase			(    self   : int			,      _a   : str			,      _a   : str					)							->       Optional[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.num_labels
										_SCREAMING_SNAKE_CASE     					=FlaxResNetForImageClassification(config=_a					)
										_SCREAMING_SNAKE_CASE     					=model(_a					)
										self.parent.assertEqual(result.logits.shape			,      (self.batch_size, self.num_labels)					)




						def 							__UpperCamelCase			(    self   : Tuple					)							->       Optional[Any]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.prepare_config_and_inputs()
										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=config_and_inputs
										_SCREAMING_SNAKE_CASE     					={'''pixel_values''': pixel_values}
										return config, inputs_dict

@require_flax
class   A__							(						UpperCamelCase__				,       unittest.TestCase					):
						UpperCAmelCase     =  (FlaxResNetModel, FlaxResNetForImageClassification) if is_flax_available() else ()

						UpperCAmelCase     =  False
						UpperCAmelCase     =  False
						UpperCAmelCase     =  False




						def 							__UpperCamelCase			(    self   : str					)							->       None:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=FlaxResNetModelTester(self					)
										_SCREAMING_SNAKE_CASE     					=ConfigTester(self			,      config_class=_a			,      has_text_modality=_a					)




						def 							__UpperCamelCase			(    self   : Optional[Any]					)							->       int:


										"""simple docstring"""





										self.create_and_test_config_common_properties()
										self.config_tester.create_and_test_config_to_json_string()
										self.config_tester.create_and_test_config_to_json_file()
										self.config_tester.create_and_test_config_from_and_save_pretrained()
										self.config_tester.create_and_test_config_with_num_labels()
										self.config_tester.check_config_can_be_init_without_params()
										self.config_tester.check_config_arguments_init()




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


										"""simple docstring"""





										return




						def 							__UpperCamelCase			(    self   : int					)							->       Optional[int]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_a					)




						def 							__UpperCamelCase			(    self   : Optional[int]					)							->       List[str]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*_a					)




						@unittest.skip(reason='''ResNet does not use inputs_embeds'''					)
						def 							__UpperCamelCase			(    self   : List[Any]					)							->       List[Any]:


										"""simple docstring"""





										pass




						@unittest.skip(reason='''ResNet does not support input and output embeddings'''					)
						def 							__UpperCamelCase			(    self   : Dict					)							->       Dict:


										"""simple docstring"""





										pass




						def 							__UpperCamelCase			(    self   : Any					)							->       int:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														_SCREAMING_SNAKE_CASE     					=model_class(_a					)
														_SCREAMING_SNAKE_CASE     					=inspect.signature(model.__call__					)
														# signature.parameters is an OrderedDict => so arg_names order is deterministic
														_SCREAMING_SNAKE_CASE     					=[*signature.parameters.keys()]

														_SCREAMING_SNAKE_CASE     					=['''pixel_values''']
														self.assertListEqual(arg_names[:1]			,      _a					)




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


										"""simple docstring"""





										def check_hidden_states_output(_a   : Optional[Any]			,      _a   : Tuple			,      _a   : Optional[Any]					):
														_SCREAMING_SNAKE_CASE     					=model_class(_a					)

														_SCREAMING_SNAKE_CASE     					=model(**self._prepare_for_class(_a			,      _a					)					)

														_SCREAMING_SNAKE_CASE     					=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

														_SCREAMING_SNAKE_CASE     					=self.model_tester.num_stages
														self.assertEqual(len(_a					)			,      expected_num_stages + 1					)




						@unittest.skip(reason='''ResNet does not use feedforward chunking'''					)
						def 							__UpperCamelCase			(    self   : Optional[int]					)							->       Dict:


										"""simple docstring"""





										pass




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


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														with self.subTest(model_class.__name__					):
																		_SCREAMING_SNAKE_CASE     					=self._prepare_for_class(_a			,      _a					)
																		_SCREAMING_SNAKE_CASE     					=model_class(_a					)

																		@jax.jit
																		def model_jitted(_a   : Optional[Any]			,      **_a   : Any					):
																						return model(pixel_values=_a			,      **_a					)

																		with self.subTest('''JIT Enabled'''					):
																						_SCREAMING_SNAKE_CASE     					=model_jitted(**_a					).to_tuple()

																		with self.subTest('''JIT Disabled'''					):
																						with jax.disable_jit():
																										_SCREAMING_SNAKE_CASE     					=model_jitted(**_a					).to_tuple()

																		self.assertEqual(len(_a					)			,      len(_a					)					)
																		for jitted_output, output in zip(_a			,      _a					):
																						self.assertEqual(jitted_output.shape			,      output.shape					)







def   lowerCamelCase(				):
				_SCREAMING_SNAKE_CASE     					=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
				return image


@require_flax
class   A__							(						unittest.TestCase					):




						@cached_property
						def 							__UpperCamelCase			(    self   : List[Any]					)							->       Any:


										"""simple docstring"""





										return AutoImageProcessor.from_pretrained('''microsoft/resnet-50'''					) if is_vision_available() else None




						@slow
						def 							__UpperCamelCase			(    self   : Union[str, Any]					)							->       Dict:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=FlaxResNetForImageClassification.from_pretrained('''microsoft/resnet-50'''					)

										_SCREAMING_SNAKE_CASE     					=self.default_image_processor
										_SCREAMING_SNAKE_CASE     					=prepare_img()
										_SCREAMING_SNAKE_CASE     					=image_processor(images=_a			,      return_tensors='''np'''					)

										_SCREAMING_SNAKE_CASE     					=model(**_a					)

										# verify the logits
										_SCREAMING_SNAKE_CASE     					=(1, 1000)
										self.assertEqual(outputs.logits.shape			,      _a					)

										_SCREAMING_SNAKE_CASE     					=jnp.array([-11.10_69, -9.78_77, -8.37_77]					)

										self.assertTrue(jnp.allclose(outputs.logits[0, :3]			,      _a			,      atol=1E-4					)					)