

import unittest

from transformers import ErnieMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import (
           ErnieMForInformationExtraction,
           ErnieMForMultipleChoice,
           ErnieMForQuestionAnswering,
           ErnieMForSequenceClassification,
           ErnieMForTokenClassification,
           ErnieMModel,
       )
       from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST







class 		__magic_name__     :

   '''simple docstring'''




   def __init__(							self,       lowercase_,       lowercase_=13,       lowercase_=7,       lowercase_=True,       lowercase_=True,       lowercase_=True,       lowercase_=99,       lowercase_=32,       lowercase_=5,       lowercase_=4,       lowercase_=37,       lowercase_="gelu",       lowercase_=0.1,       lowercase_=0.1,       lowercase_=512,       lowercase_=16,       lowercase_=2,       lowercase_=0.02,       lowercase_=3,       lowercase_=4,       lowercase_=None,       )				->       str:






     """simple docstring"""






     a__    =parent
     a__    =batch_size
     a__    =seq_length
     a__    =is_training
     a__    =use_input_mask
     a__    =use_labels
     a__    =vocab_size
     a__    =hidden_size
     a__    =num_hidden_layers
     a__    =num_attention_heads
     a__    =intermediate_size
     a__    =hidden_act
     a__    =hidden_dropout_prob
     a__    =attention_probs_dropout_prob
     a__    =max_position_embeddings
     a__    =type_vocab_size
     a__    =type_sequence_label_size
     a__    =initializer_range
     a__    =num_labels
     a__    =num_choices
     a__    =scope



   def 					_UpperCAmelCase					(							self			)				->       List[str]:






     """simple docstring"""






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

     a__    =None
     if self.use_input_mask:
       a__    =random_attention_mask([self.batch_size, self.seq_length]			)

     a__    =None
     a__    =None
     a__    =None
     if self.use_labels:
       a__    =ids_tensor([self.batch_size],       self.type_sequence_label_size			)
       a__    =ids_tensor([self.batch_size, self.seq_length],       self.num_labels			)
       a__    =ids_tensor([self.batch_size],       self.num_choices			)

     a__    =self.get_config()

     return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels



   def 					_UpperCAmelCase					(							self			)				->       List[str]:






     """simple docstring"""






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

     a__    =None
     if self.use_input_mask:
       a__    =random_attention_mask([self.batch_size, self.seq_length]			)
     a__    =self.get_config()

     return config, input_ids, input_mask



   def 					_UpperCAmelCase					(							self			)				->       Any:






     """simple docstring"""






     return ErnieMConfig(
         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,       initializer_range=self.initializer_range,       )



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_			)				->       str:






     """simple docstring"""






     a__    =ErnieMModel(config=snake_case_			)
     model.to(snake_case_			)
     model.eval()
     a__    =model(snake_case_,       return_dict=snake_case_			)
     self.parent.assertEqual(result.last_hidden_state.shape,       (self.batch_size, self.seq_length, self.hidden_size)			)



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_			)				->       int:






     """simple docstring"""






     a__    =ErnieMForQuestionAnswering(config=snake_case_			)
     model.to(snake_case_			)
     model.eval()
     a__    =model(
         snake_case_,       attention_mask=snake_case_,       start_positions=snake_case_,       end_positions=snake_case_,       )
     self.parent.assertEqual(result.start_logits.shape,       (self.batch_size, self.seq_length)			)
     self.parent.assertEqual(result.end_logits.shape,       (self.batch_size, self.seq_length)			)



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_			)				->       Dict:






     """simple docstring"""






     a__    =ErnieMForInformationExtraction(config=snake_case_			)
     model.to(snake_case_			)
     model.eval()
     a__    =torch.ones_like(snake_case_,       dtype=torch.floataa			)
     a__    =model(
         snake_case_,       attention_mask=snake_case_,       start_positions=snake_case_,       end_positions=snake_case_,       )
     self.parent.assertEqual(result.start_logits.shape,       (self.batch_size, self.seq_length)			)
     self.parent.assertEqual(result.end_logits.shape,       (self.batch_size, self.seq_length)			)



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_			)				->       Optional[int]:






     """simple docstring"""






     a__    =self.num_labels
     a__    =ErnieMForSequenceClassification(snake_case_			)
     model.to(snake_case_			)
     model.eval()
     a__    =model(snake_case_,       attention_mask=snake_case_,       labels=snake_case_			)
     self.parent.assertEqual(result.logits.shape,       (self.batch_size, self.num_labels)			)



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_			)				->       List[Any]:






     """simple docstring"""






     a__    =self.num_labels
     a__    =ErnieMForTokenClassification(config=snake_case_			)
     model.to(snake_case_			)
     model.eval()
     input_ids.to(snake_case_			)
     input_mask.to(snake_case_			)
     token_labels.to(snake_case_			)

     a__    =model(snake_case_,       attention_mask=snake_case_,       labels=snake_case_			)

     self.parent.assertEqual(result.logits.shape,       (self.batch_size, self.seq_length, self.num_labels)			)



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_			)				->       Any:






     """simple docstring"""






     a__    =self.num_choices
     a__    =ErnieMForMultipleChoice(config=snake_case_			)
     model.to(snake_case_			)
     model.eval()
     a__    =input_ids.unsqueeze(1			).expand(-1,       self.num_choices,       -1			).contiguous()
     a__    =input_mask.unsqueeze(1			).expand(-1,       self.num_choices,       -1			).contiguous()
     a__    =model(
         snake_case_,       attention_mask=snake_case_,       labels=snake_case_,       )
     self.parent.assertEqual(result.logits.shape,       (self.batch_size, self.num_choices)			)



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






     """simple docstring"""






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







@require_torch
class 		__magic_name__     (				_UpperCAmelCase						,			_UpperCAmelCase						,			unittest.TestCase				):

   '''simple docstring'''




   lowerCamelCase__					:      int        =  (
       (
           ErnieMModel,
           ErnieMForMultipleChoice,
           ErnieMForQuestionAnswering,
           ErnieMForSequenceClassification,
           ErnieMForTokenClassification,
       )
       if is_torch_available()
       else ()
   )
   lowerCamelCase__					:      Any        =  ()
   lowerCamelCase__					:      Dict        =  (
       {
           """feature-extraction""": ErnieMModel,
           """question-answering""": ErnieMForQuestionAnswering,
           """text-classification""": ErnieMForSequenceClassification,
           """token-classification""": ErnieMForTokenClassification,
           """zero-shot""": ErnieMForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   lowerCamelCase__					:      int        =  False



   def 					_UpperCAmelCase					(							self,       lowercase_,       lowercase_,       lowercase_,       lowercase_,       lowercase_			)				->       List[Any]:






     """simple docstring"""






     if pipeline_test_casse_name == "QAPipelineTests":
       return True

     return False



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






     """simple docstring"""






     a__    =ErnieMModelTester(self			)
     a__    =ConfigTester(self,       config_class=snake_case_,       hidden_size=37			)



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






     """simple docstring"""






     self.config_tester.run_common_tests()



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






     """simple docstring"""






     a__    =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*snake_case_			)



   def 					_UpperCAmelCase					(							self			)				->       Any:






     """simple docstring"""






     a__    =self.model_tester.prepare_config_and_inputs()
     for type in ["absolute", "relative_key", "relative_key_query"]:
       a__    =type
       self.model_tester.create_and_check_model(*snake_case_			)



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






     """simple docstring"""






     a__    =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_multiple_choice(*snake_case_			)



   def 					_UpperCAmelCase					(							self			)				->       List[str]:






     """simple docstring"""






     a__    =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_question_answering(*snake_case_			)



   def 					_UpperCAmelCase					(							self			)				->       Tuple:






     """simple docstring"""






     a__    =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_sequence_classification(*snake_case_			)



   def 					_UpperCAmelCase					(							self			)				->       int:






     """simple docstring"""






     a__    =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_information_extraction(*snake_case_			)



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






     """simple docstring"""






     a__    =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_token_classification(*snake_case_			)



   @slow
   def 					_UpperCAmelCase					(							self			)				->       str:






     """simple docstring"""






     for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       a__    =ErnieMModel.from_pretrained(snake_case_			)
       self.assertIsNotNone(snake_case_			)







@require_torch
class 		__magic_name__     (				unittest.TestCase				):

   '''simple docstring'''




   @slow
   def 					_UpperCAmelCase					(							self			)				->       Any:






     """simple docstring"""






     a__    =ErnieMModel.from_pretrained('''susnato/ernie-m-base_pytorch'''			)
     model.eval()
     a__    =torch.tensor([[0, 1, 2, 3, 4, 5]]			)
     a__    =model(snake_case_			)[0]

     # TODO Replace vocab size
     a__    =768

     a__    =torch.Size((1, 6, hidden_size)			)
     self.assertEqual(output.shape,       snake_case_			)

     a__    =torch.tensor(
         [[[-0.0012, 0.1245, -0.0214], [-0.0742, 0.0244, -0.0771], [-0.0333, 0.1164, -0.1554]]]			)

     self.assertTrue(torch.allclose(output[:, :3, :3],       snake_case_,       atol=1E-3			)			)

'''simple docstring'''

import unittest

import requests

from transformers import MODEL_FOR_VISION_2_SEQ_MAPPING, TF_MODEL_FOR_VISION_2_SEQ_MAPPING, is_vision_available
from transformers.pipelines import pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    is_torch_available,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_torch_available():
						from transformers.pytorch_utils import is_torch_greater_or_equal_than_1_11
else:
						A_	   = False


if is_vision_available():
						from PIL import Image
else:




						class 		SCREAMING_SNAKE_CASE_					:



									"""simple docstring"""






									@staticmethod
									def   lowerCamelCase (							*snake_case_				,			**snake_case_					):
															pass




@is_pipeline_test
@require_vision
class 		SCREAMING_SNAKE_CASE_					(unittest.TestCase      ):



			"""simple docstring"""






			__magic_name__ :				Optional[int]   							=       MODEL_FOR_VISION_2_SEQ_MAPPING
			__magic_name__ :				Optional[int]   							=       TF_MODEL_FOR_VISION_2_SEQ_MAPPING



			def   lowerCamelCase (							self				,			snake_case_				,			snake_case_				,			snake_case_					):
									snake_case :       str				=    pipeline("image-to-text"				,			model=snake_case_				,			tokenizer=snake_case_				,			image_processor=snake_case_					)
									snake_case :       List[Any]				=    [
									    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"					),
									    "./tests/fixtures/tests_samples/COCO/000000039769.png",
									]
									return pipe, examples



			def   lowerCamelCase (							self				,			snake_case_				,			snake_case_					):
									snake_case :       Union[str, Any]				=    pipe(snake_case_					)
									self.assertEqual(
									    snake_case_				,			[
									        [{"generated_text": ANY(snake_case_					)}],
									        [{"generated_text": ANY(snake_case_					)}],
									    ]				,			)



			@require_tf
			def   lowerCamelCase (							self					):
									snake_case :       Tuple				=    pipeline("image-to-text"				,			model="hf-internal-testing/tiny-random-vit-gpt2"				,			framework="tf"					)
									snake_case :       Union[str, Any]				=    "./tests/fixtures/tests_samples/COCO/000000039769.png"

									snake_case :       Dict				=    pipe(snake_case_					)
									self.assertEqual(
									    snake_case_				,			[
									        {
									            "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									        },
									    ]				,			)

									snake_case :       Tuple				=    pipe([image, image]					)
									self.assertEqual(
									    snake_case_				,			[
									        [
									            {
									                "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									            }
									        ],
									        [
									            {
									                "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									            }
									        ],
									    ]				,			)

									snake_case :       List[Any]				=    pipe(snake_case_				,			max_new_tokens=1					)
									self.assertEqual(
									    snake_case_				,			[{"generated_text": "growth"}]				,			)



			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       List[Any]				=    pipeline("image-to-text"				,			model="hf-internal-testing/tiny-random-vit-gpt2"					)
									snake_case :       Tuple				=    "./tests/fixtures/tests_samples/COCO/000000039769.png"

									snake_case :       Any				=    pipe(snake_case_					)
									self.assertEqual(
									    snake_case_				,			[
									        {
									            "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									        },
									    ]				,			)

									snake_case :       str				=    pipe([image, image]					)
									self.assertEqual(
									    snake_case_				,			[
									        [
									            {
									                "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									            }
									        ],
									        [
									            {
									                "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO"
									            }
									        ],
									    ]				,			)



			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       Tuple				=    pipeline("image-to-text"				,			model="hf-internal-testing/tiny-random-BlipForConditionalGeneration"					)
									snake_case :       Dict				=    "./tests/fixtures/tests_samples/COCO/000000039769.png"
									snake_case :       List[Any]				=    "a photo of"

									snake_case :       List[str]				=    pipe(snake_case_				,			prompt=snake_case_					)
									self.assertTrue(outputs[0]["generated_text"].startswith(snake_case_					)					)



			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       Optional[Any]				=    pipeline("image-to-text"				,			model="ydshieh/vit-gpt2-coco-en"					)
									snake_case :       Union[str, Any]				=    "./tests/fixtures/tests_samples/COCO/000000039769.png"

									snake_case :       Tuple				=    pipe(snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}]					)

									snake_case :       Tuple				=    pipe([image, image]					)
									self.assertEqual(
									    snake_case_				,			[
									        [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
									        [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
									    ]				,			)



			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       Optional[Any]				=    pipeline("image-to-text"				,			model="Salesforce/blip-image-captioning-base"					)
									snake_case :       Any				=    "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
									snake_case :       Union[str, Any]				=    Image.open(requests.get(snake_case_				,			stream=snake_case_					).raw					)

									snake_case :       Optional[Any]				=    pipe(snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a pink pokemon pokemon with a blue shirt and a blue shirt"}]					)



			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       Tuple				=    pipeline("image-to-text"				,			model="microsoft/git-base-coco"					)
									snake_case :       Tuple				=    "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png"
									snake_case :       Tuple				=    Image.open(requests.get(snake_case_				,			stream=snake_case_					).raw					)

									snake_case :       Any				=    pipe(snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a cartoon of a purple character."}]					)



			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       Optional[Any]				=    pipeline("image-to-text"				,			model="Salesforce/blip-image-captioning-base"					)
									snake_case :       int				=    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
									snake_case :       Tuple				=    Image.open(requests.get(snake_case_				,			stream=snake_case_					).raw					)

									snake_case :       str				=    "a photography of"

									snake_case :       int				=    pipe(snake_case_				,			prompt=snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a photography of a volcano"}]					)

									with self.assertRaises(snake_case_					):
															snake_case :       List[Any]				=    pipe([image, image]				,			prompt=[prompt, prompt]					)



			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       List[str]				=    pipeline("image-to-text"				,			model="microsoft/git-base-coco"					)
									snake_case :       Optional[Any]				=    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
									snake_case :       List[str]				=    Image.open(requests.get(snake_case_				,			stream=snake_case_					).raw					)

									snake_case :       Any				=    "a photo of a"

									snake_case :       Dict				=    pipe(snake_case_				,			prompt=snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a photo of a tent with a tent and a tent in the background."}]					)

									with self.assertRaises(snake_case_					):
															snake_case :       List[str]				=    pipe([image, image]				,			prompt=[prompt, prompt]					)



			@unittest.skipIf(
			    not is_torch_greater_or_equal_than_1_11				,			reason="`Pix2StructImageProcessor` requires `torch>=1.11.0`."					)
			@slow
			@require_torch
			def   lowerCamelCase (							self					):
									snake_case :       List[str]				=    pipeline("image-to-text"				,			model="google/pix2struct-ai2d-base"					)
									snake_case :       Optional[int]				=    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
									snake_case :       str				=    Image.open(requests.get(snake_case_				,			stream=snake_case_					).raw					)

									snake_case :       Any				=    "What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud"

									snake_case :       str				=    pipe(snake_case_				,			prompt=snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "ash cloud"}]					)

									with self.assertRaises(snake_case_					):
															snake_case :       List[str]				=    pipe([image, image]				,			prompt=[prompt, prompt]					)






			@slow
			@require_tf
			def   lowerCamelCase (							self					):
									snake_case :       List[str]				=    pipeline("image-to-text"				,			model="ydshieh/vit-gpt2-coco-en"				,			framework="tf"					)
									snake_case :       Union[str, Any]				=    "./tests/fixtures/tests_samples/COCO/000000039769.png"

									snake_case :       Any				=    pipe(snake_case_					)
									self.assertEqual(snake_case_				,			[{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}]					)

									snake_case :       Optional[int]				=    pipe([image, image]					)
									self.assertEqual(
									    snake_case_				,			[
									        [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
									        [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}],
									    ]				,			)





