


import inspect
import unittest

from transformers import MobileNetVaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
  import torch

  from transformers import MobileNetVaForImageClassification, MobileNetVaModel
  from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import MobileNetVaImageProcessor







class _lowerCAmelCase    (				snake_case_     ):







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

       '''simple docstring'''




       snake_case   :				Tuple				 =   self.config_class(**self.inputs_dict						)
       self.parent.assertTrue(hasattr(UpperCamelCase__						,     "tf_padding"						)						)
       self.parent.assertTrue(hasattr(UpperCamelCase__						,     "depth_multiplier"						)						)







class _lowerCAmelCase    :







   def __init__(     self						,     UpperCamelCase__						,     UpperCamelCase__=13						,     UpperCamelCase__=3						,     UpperCamelCase__=32						,     UpperCamelCase__=0.25						,     UpperCamelCase__=8						,     UpperCamelCase__=True						,     UpperCamelCase__=1024						,     UpperCamelCase__=32						,     UpperCamelCase__="relu6"						,     UpperCamelCase__=0.1						,     UpperCamelCase__=0.02						,     UpperCamelCase__=True						,     UpperCamelCase__=True						,     UpperCamelCase__=10						,     UpperCamelCase__=None						,     )     ->		List[Any]:

       '''simple docstring'''




       snake_case   :				int				 =   parent
       snake_case   :				int				 =   batch_size
       snake_case   :				List[Any]				 =   num_channels
       snake_case   :				Any				 =   image_size
       snake_case   :				str				 =   depth_multiplier
       snake_case   :				Dict				 =   min_depth
       snake_case   :				List[Any]				 =   tf_padding
       snake_case   :				Tuple				 =   int(last_hidden_size * depth_multiplier						)
       snake_case   :				Tuple				 =   output_stride
       snake_case   :				int				 =   hidden_act
       snake_case   :				int				 =   classifier_dropout_prob
       snake_case   :				Any				 =   use_labels
       snake_case   :				Union[str, Any]				 =   is_training
       snake_case   :				Dict				 =   num_labels
       snake_case   :				Dict				 =   initializer_range
       snake_case   :				Optional[Any]				 =   scope







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

       '''simple docstring'''




       snake_case   :				Optional[int]				 =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       snake_case   :				str				 =   None
       snake_case   :				Dict				 =   None
       if self.use_labels:
           snake_case   :				Union[str, Any]				 =   ids_tensor([self.batch_size]						,     self.num_labels						)
           snake_case   :				Optional[Any]				 =   ids_tensor([self.batch_size, self.image_size, self.image_size]						,     self.num_labels						)

       snake_case   :				Optional[int]				 =   self.get_config()

       return config, pixel_values, labels, pixel_labels







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

       '''simple docstring'''




       return MobileNetVaConfig(
           num_channels=self.num_channels						,     image_size=self.image_size						,     depth_multiplier=self.depth_multiplier						,     min_depth=self.min_depth						,     tf_padding=self.tf_padding						,     hidden_act=self.hidden_act						,     classifier_dropout_prob=self.classifier_dropout_prob						,     initializer_range=self.initializer_range						,     )







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

       '''simple docstring'''




       snake_case   :				Union[str, Any]				 =   MobileNetVaModel(config=UpperCamelCase__						)
       model.to(UpperCamelCase__						)
       model.eval()
       snake_case   :				Tuple				 =   model(UpperCamelCase__						)
       self.parent.assertEqual(
           result.last_hidden_state.shape						,     (
               self.batch_size,
               self.last_hidden_size,
               self.image_size // self.output_stride,
               self.image_size // self.output_stride,
           )						,     )







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)     ->		Optional[int]:

       '''simple docstring'''




       snake_case   :				List[str]				 =   self.num_labels
       snake_case   :				int				 =   MobileNetVaForImageClassification(UpperCamelCase__						)
       model.to(UpperCamelCase__						)
       model.eval()
       snake_case   :				Tuple				 =   model(UpperCamelCase__						,     labels=UpperCamelCase__						)
       self.parent.assertEqual(result.logits.shape						,     (self.batch_size, self.num_labels)						)







   def 			lowerCamelCase		(     self						)     ->		Any:

       '''simple docstring'''




       snake_case   :				Any				 =   self.prepare_config_and_inputs()
       snake_case   :				List[str]				 =   config_and_inputs
       snake_case   :				Tuple				 =   {"pixel_values": pixel_values}
       return config, inputs_dict







@require_torch
class _lowerCAmelCase    (				snake_case_   ,							snake_case_   ,							unittest.TestCase     ):
   __UpperCAmelCase			:	List[str]							  =  (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
   __UpperCAmelCase			:	Tuple							  =  (
       {'''feature-extraction''': MobileNetVaModel, '''image-classification''': MobileNetVaForImageClassification}
       if is_torch_available()
       else {}
   )

   __UpperCAmelCase			:	Any							  =  False
   __UpperCAmelCase			:	int							  =  False
   __UpperCAmelCase			:	Optional[Any]							  =  False
   __UpperCAmelCase			:	str							  =  False







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

       '''simple docstring'''




       snake_case   :				List[str]				 =   MobileNetVaModelTester(self						)
       snake_case   :				Union[str, Any]				 =   MobileNetVaConfigTester(self						,     config_class=UpperCamelCase__						,     has_text_modality=UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		Tuple:

       '''simple docstring'''




       self.config_tester.run_common_tests()







   @unittest.skip(reason="MobileNetV1 does not use inputs_embeds"						)
   def 			lowerCamelCase		(     self						)     ->		int:

       '''simple docstring'''




       pass







   @unittest.skip(reason="MobileNetV1 does not support input and output embeddings"						)
   def 			lowerCamelCase		(     self						)     ->		Optional[Any]:

       '''simple docstring'''




       pass







   @unittest.skip(reason="MobileNetV1 does not output attentions"						)
   def 			lowerCamelCase		(     self						)     ->		Dict:

       '''simple docstring'''




       pass







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

       '''simple docstring'''




       snake_case   :				str				 =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           snake_case   :				List[Any]				 =   model_class(UpperCamelCase__						)
           snake_case   :				List[str]				 =   inspect.signature(model.forward						)
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           snake_case   :				int				 =   [*signature.parameters.keys()]

           snake_case   :				List[str]				 =   ["pixel_values"]
           self.assertListEqual(arg_names[:1]						,     UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		Tuple:

       '''simple docstring'''




       snake_case   :				Tuple				 =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCamelCase__						)







   def 			lowerCamelCase		(     self						)     ->		Tuple:

       '''simple docstring'''




       def check_hidden_states_output(UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						):
           snake_case   :				Union[str, Any]				 =   model_class(UpperCamelCase__						)
           model.to(UpperCamelCase__						)
           model.eval()

           with torch.no_grad():
               snake_case   :				Any				 =   model(**self._prepare_for_class(UpperCamelCase__						,     UpperCamelCase__						)						)

           snake_case   :				str				 =   outputs.hidden_states

           snake_case   :				List[str]				 =   26
           self.assertEqual(len(UpperCamelCase__						)						,     UpperCamelCase__						)

       snake_case   :				Dict				 =   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           snake_case   :				Optional[int]				 =   True
           check_hidden_states_output(UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           snake_case   :				str				 =   True

           check_hidden_states_output(UpperCamelCase__						,     UpperCamelCase__						,     UpperCamelCase__						)







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

       '''simple docstring'''




       snake_case   :				List[str]				 =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__						)







   @slow
   def 			lowerCamelCase		(     self						)     ->		str:

       '''simple docstring'''




       for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           snake_case   :				Union[str, Any]				 =   MobileNetVaModel.from_pretrained(UpperCamelCase__						)
           self.assertIsNotNone(UpperCamelCase__						)







def   __lowerCAmelCase						(						)     ->						List[str]:


    """simple docstring"""





    snake_case   :				int				 =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
    return image







@require_torch
@require_vision
class _lowerCAmelCase    (				unittest.TestCase     ):







   @cached_property
   def 			lowerCamelCase		(     self						)     ->		int:

       '''simple docstring'''




       return (
           MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224"						) if is_vision_available() else None
       )







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

       '''simple docstring'''




       snake_case   :				List[str]				 =   MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224"						).to(UpperCamelCase__						)

       snake_case   :				List[Any]				 =   self.default_image_processor
       snake_case   :				Dict				 =   prepare_img()
       snake_case   :				Optional[int]				 =   image_processor(images=UpperCamelCase__						,     return_tensors="pt"						).to(UpperCamelCase__						)

       # forward pass
       with torch.no_grad():
           snake_case   :				Any				 =   model(**UpperCamelCase__						)

       # verify the logits
       snake_case   :				List[Any]				 =   torch.Size((1, 1001)						)
       self.assertEqual(outputs.logits.shape						,     UpperCamelCase__						)

       snake_case   :				Any				 =   torch.tensor([-4.1739, -1.1233, 3.1205]						).to(UpperCamelCase__						)

       self.assertTrue(torch.allclose(outputs.logits[0, :3]						,     UpperCamelCase__						,     atol=1e-4						)						)









"""simple docstring"""



import json
import os
import unittest

from transformers import MgpstrTokenizer
from transformers.models.mgp_str.tokenization_mgp_str import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin







@require_tokenizers
class _lowerCAmelCase    (				snake_case_   ,							unittest.TestCase     ):
   __UpperCAmelCase			:	List[Any]							  =  MgpstrTokenizer
   __UpperCAmelCase			:	Optional[int]							  =  False
   __UpperCAmelCase			:	Optional[int]							  =  {}
   __UpperCAmelCase			:	List[str]							  =  False







   def 			lowerCamelCase		(     self						)     ->		int:

       '''simple docstring'''




       super().setUp()

       # fmt: off
       snake_case   :				List[str]				 =   ["[GO]", "[s]", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
       # fmt: on
       snake_case   :				Union[str, Any]				 =   dict(zip(UpperCamelCase__						,     range(len(UpperCamelCase__						)						)						)						)

       snake_case   :				int				 =   os.path.join(self.tmpdirname						,     VOCAB_FILES_NAMES["vocab_file"]						)
       with open(self.vocab_file						,     "w"						,     encoding="utf-8"						) as fp:
           fp.write(json.dumps(UpperCamelCase__						) + "\n"						)







   def 			lowerCamelCase		(     self						,     **UpperCamelCase__						)     ->		List[str]:

       '''simple docstring'''




       return MgpstrTokenizer.from_pretrained(self.tmpdirname						,     **UpperCamelCase__						)







   def 			lowerCamelCase		(     self						,     UpperCamelCase__						)     ->		List[Any]:

       '''simple docstring'''




       snake_case   :				int				 =   "tester"
       snake_case   :				List[str]				 =   "tester"
       return input_text, output_text







   @unittest.skip("MGP-STR always lower cases letters."						)
   def 			lowerCamelCase		(     self						)     ->		str:

       '''simple docstring'''




       pass







   def 			lowerCamelCase		(     self						)     ->		Tuple:

       '''simple docstring'''




       snake_case   :				int				 =   self.get_tokenizers(do_lower_case=UpperCamelCase__						)
       for tokenizer in tokenizers:
           with self.subTest(F'{tokenizer.__class__.__name__}'						):
               snake_case   :				List[Any]				 =   "[SPECIAL_TOKEN]"

               tokenizer.add_special_tokens({"cls_token": special_token}						)
               snake_case   :				str				 =   tokenizer.encode([special_token]						,     add_special_tokens=UpperCamelCase__						)
               self.assertEqual(len(UpperCamelCase__						)						,     1						)

               snake_case   :				List[Any]				 =   tokenizer.decode(UpperCamelCase__						,     skip_special_tokens=UpperCamelCase__						)
               self.assertTrue(special_token not in decoded						)







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

       '''simple docstring'''




       snake_case   :				List[str]				 =   self.get_tokenizers()
       for tokenizer in tokenizers:
           with self.subTest(F'{tokenizer.__class__.__name__}'						):
               snake_case ,snake_case   :				Union[str, Any]				 =   self.get_input_output_texts(UpperCamelCase__						)

               snake_case   :				Dict				 =   tokenizer.tokenize(UpperCamelCase__						)
               snake_case   :				Tuple				 =   tokenizer.convert_tokens_to_ids(UpperCamelCase__						)
               snake_case   :				List[Any]				 =   tokenizer.encode(UpperCamelCase__						,     add_special_tokens=UpperCamelCase__						)
               self.assertListEqual(UpperCamelCase__						,     UpperCamelCase__						)

               snake_case   :				Dict				 =   tokenizer.convert_ids_to_tokens(UpperCamelCase__						)
               self.assertNotEqual(len(UpperCamelCase__						)						,     0						)
               snake_case   :				Tuple				 =   tokenizer.decode(UpperCamelCase__						)
               self.assertIsInstance(UpperCamelCase__						,     UpperCamelCase__						)

               self.assertEqual(text_a.replace(" "						,     ""						)						,     UpperCamelCase__						)







   @unittest.skip("MGP-STR tokenizer only handles one sequence."						)
   def 			lowerCamelCase		(     self						)     ->		List[Any]:

       '''simple docstring'''




       pass







   @unittest.skip("inputs cannot be pretokenized in MgpstrTokenizer"						)
   def 			lowerCamelCase		(     self						)     ->		Tuple:

       '''simple docstring'''




       pass





