

"""simple docstring"""




import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
	from PIL import Image
else:





	class 			__UpperCamelCase :


			@staticmethod
			def 					SCREAMING_SNAKE_CASE__   (*__SCREAMING_SNAKE_CASE :		str     ,     **__SCREAMING_SNAKE_CASE :		Dict):
								pass





@is_pipeline_test
@require_torch_or_tf
@require_vision
class 			__UpperCamelCase (   unittest.TestCase						):
		SCREAMING_SNAKE_CASE								=    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
		SCREAMING_SNAKE_CASE								=    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING


		def 					SCREAMING_SNAKE_CASE__   (self :		Dict     ,     __SCREAMING_SNAKE_CASE :		Optional[Any]     ,     __SCREAMING_SNAKE_CASE :		Tuple     ,     __SCREAMING_SNAKE_CASE :		Optional[int]):
							A			=					ImageClassificationPipeline(model=__SCREAMING_SNAKE_CASE     ,     image_processor=__SCREAMING_SNAKE_CASE     ,     top_k=2)
							A			=					[
							    Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"),
							    "http://images.cocodataset.org/val2017/000000039769.jpg",
							]
							return image_classifier, examples


		def 					SCREAMING_SNAKE_CASE__   (self :		List[str]     ,     __SCREAMING_SNAKE_CASE :		Optional[Any]     ,     __SCREAMING_SNAKE_CASE :		Any):
							A			=					image_classifier("./tests/fixtures/tests_samples/COCO/000000039769.png")

							self.assertEqual(
							    __SCREAMING_SNAKE_CASE     ,     [
							        {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							    ]     ,     )

							import datasets

							A			=					datasets.load_dataset("hf-internal-testing/fixtures_image_utils"     ,     "image"     ,     split="test")

							# Accepts URL + PIL.Image + lists
							A			=					image_classifier(
							    [
							        Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"),
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							        # RGBA
							        dataset[0]["file"],
							        # LA
							        dataset[1]["file"],
							        # L
							        dataset[2]["file"],
							    ])
							self.assertEqual(
							    __SCREAMING_SNAKE_CASE     ,     [
							        [
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        ],
							        [
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        ],
							        [
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        ],
							        [
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        ],
							        [
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							            {"score": ANY(__SCREAMING_SNAKE_CASE), "label": ANY(__SCREAMING_SNAKE_CASE)},
							        ],
							    ]     ,     )


		@require_torch
		def 					SCREAMING_SNAKE_CASE__   (self :		Optional[Any]):
							A			=					"hf-internal-testing/tiny-random-vit"
							A			=					pipeline("image-classification"     ,     model=__SCREAMING_SNAKE_CASE)

							A			=					image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE     ,     decimals=4)     ,     [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}]     ,     )

							A			=					image_classifier(
							    [
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							    ]     ,     top_k=2     ,     )
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE     ,     decimals=4)     ,     [
							        [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
							        [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
							    ]     ,     )


		@require_tf
		def 					SCREAMING_SNAKE_CASE__   (self :		Optional[int]):
							A			=					"hf-internal-testing/tiny-random-vit"
							A			=					pipeline("image-classification"     ,     model=__SCREAMING_SNAKE_CASE     ,     framework="tf")

							A			=					image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE     ,     decimals=4)     ,     [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}]     ,     )

							A			=					image_classifier(
							    [
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							        "http://images.cocodataset.org/val2017/000000039769.jpg",
							    ]     ,     top_k=2     ,     )
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE     ,     decimals=4)     ,     [
							        [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
							        [{"label": "LABEL_1", "score": 0.5_7_4}, {"label": "LABEL_0", "score": 0.4_2_6}],
							    ]     ,     )


		def 					SCREAMING_SNAKE_CASE__   (self :		Tuple):
							A			=					PreTrainedTokenizer()

							# Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
							A			=					pipeline(
							    "image-classification"     ,     model="hf-internal-testing/tiny-random-vit"     ,     tokenizer=__SCREAMING_SNAKE_CASE)

							self.assertIs(image_classifier.tokenizer     ,     __SCREAMING_SNAKE_CASE)


		@slow
		@require_torch
		def 					SCREAMING_SNAKE_CASE__   (self :		Union[str, Any]):
							# Perceiver is not tested by `run_pipeline_test` properly.
							# That is because the type of feature_extractor and model preprocessor need to be kept
							# in sync, which is not the case in the current design
							A			=					pipeline("image-classification"     ,     model="deepmind/vision-perceiver-conv")
							A			=					image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE     ,     decimals=4)     ,     [
							        {"score": 0.4_3_8_5, "label": "tabby, tabby cat"},
							        {"score": 0.3_2_1, "label": "tiger cat"},
							        {"score": 0.0_5_0_2, "label": "Egyptian cat"},
							        {"score": 0.0_1_3_7, "label": "crib, cot"},
							        {"score": 0.0_0_7, "label": "radiator"},
							    ]     ,     )

							A			=					pipeline("image-classification"     ,     model="deepmind/vision-perceiver-fourier")
							A			=					image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE     ,     decimals=4)     ,     [
							        {"score": 0.5_6_5_8, "label": "tabby, tabby cat"},
							        {"score": 0.1_3_0_9, "label": "tiger cat"},
							        {"score": 0.0_7_2_2, "label": "Egyptian cat"},
							        {"score": 0.0_7_0_7, "label": "remote control, remote"},
							        {"score": 0.0_0_8_2, "label": "computer keyboard, keypad"},
							    ]     ,     )

							A			=					pipeline("image-classification"     ,     model="deepmind/vision-perceiver-learned")
							A			=					image_classifier("http://images.cocodataset.org/val2017/000000039769.jpg")
							self.assertEqual(
							    nested_simplify(__SCREAMING_SNAKE_CASE     ,     decimals=4)     ,     [
							        {"score": 0.3_0_2_2, "label": "tabby, tabby cat"},
							        {"score": 0.2_3_6_2, "label": "Egyptian cat"},
							        {"score": 0.1_8_5_6, "label": "tiger cat"},
							        {"score": 0.0_3_2_4, "label": "remote control, remote"},
							        {"score": 0.0_0_9_6, "label": "quilt, comforter, comfort, puff"},
							    ]     ,     )













"""simple docstring"""







import unittest

import numpy as np

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

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
 from transformers.models.electra.modeling_flax_electra import (
     FlaxElectraForCausalLM,
     FlaxElectraForMaskedLM,
     FlaxElectraForMultipleChoice,
     FlaxElectraForPreTraining,
     FlaxElectraForQuestionAnswering,
     FlaxElectraForSequenceClassification,
     FlaxElectraForTokenClassification,
     FlaxElectraModel,
 )





class      UpperCamelCase_       (				unittest.TestCase     ):



  def __init__(					self       ,						snake_case__       ,						snake_case__=13       ,						snake_case__=7       ,						snake_case__=True       ,						snake_case__=True       ,						snake_case__=True       ,						snake_case__=True       ,						snake_case__=99       ,						snake_case__=24       ,						snake_case__=32       ,						snake_case__=5       ,						snake_case__=4       ,						snake_case__=37       ,						snake_case__="gelu"       ,						snake_case__=0.1       ,						snake_case__=0.1       ,						snake_case__=5_12       ,						snake_case__=16       ,						snake_case__=2       ,						snake_case__=0.02       ,						snake_case__=4       ,						)	->	int:



         """simple docstring"""





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



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



         """simple docstring"""





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

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

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

         UpperCAmelCase					=	ElectraConfig(
             vocab_size=self.vocab_size       ,						hidden_size=self.hidden_size       ,						embedding_size=self.embedding_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       ,						)

         return config, input_ids, token_type_ids, attention_mask



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



         """simple docstring"""





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





@require_flax
class      UpperCamelCase_       (				a_      ,    unittest.TestCase     ):
  _A				:    str =		True

  _A				:    List[Any] =		(
      (
          FlaxElectraModel,
          FlaxElectraForCausalLM,
          FlaxElectraForMaskedLM,
          FlaxElectraForPreTraining,
          FlaxElectraForTokenClassification,
          FlaxElectraForQuestionAnswering,
          FlaxElectraForMultipleChoice,
          FlaxElectraForSequenceClassification,
      )
      if is_flax_available()
      else ()
  )



  def 						UpperCamelCase_ (					self )	->	str:



         """simple docstring"""





         UpperCAmelCase					=	FlaxElectraModelTester(self )



  @slow
  def 						UpperCamelCase_ (					self )	->	Tuple:



         """simple docstring"""





         for model_class_name in self.all_model_classes:
                if model_class_name == FlaxElectraForMaskedLM:
                       UpperCAmelCase					=	model_class_name.from_pretrained("""google/electra-small-generator""" )
                else:
                       UpperCAmelCase					=	model_class_name.from_pretrained("""google/electra-small-discriminator""" )
                UpperCAmelCase					=	model(np.ones((1, 1) ) )
                self.assertIsNotNone(snake_case__ )
