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 					A							(    UpperCAmelCase_					):


   def       lowercase_				(self					:						Dict		)						->    Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.config_class(**self.inputs_dict		)
         self.parent.assertTrue(hasattr(__UpperCAmelCase	,  "tf_padding"		)		)
         self.parent.assertTrue(hasattr(__UpperCAmelCase	,  "depth_multiplier"		)		)





class 					A							:


   def __init__(self					:						str	,  __UpperCAmelCase					:						Optional[int]	,  __UpperCAmelCase					:						Dict=1_3	,  __UpperCAmelCase					:						str=3	,  __UpperCAmelCase					:						List[Any]=3_2	,  __UpperCAmelCase					:						str=0.25	,  __UpperCAmelCase					:						Dict=8	,  __UpperCAmelCase					:						Tuple=True	,  __UpperCAmelCase					:						int=1_0_2_4	,  __UpperCAmelCase					:						Any=3_2	,  __UpperCAmelCase					:						Optional[Any]="relu6"	,  __UpperCAmelCase					:						List[Any]=0.1	,  __UpperCAmelCase					:						List[Any]=0.02	,  __UpperCAmelCase					:						Dict=True	,  __UpperCAmelCase					:						Optional[int]=True	,  __UpperCAmelCase					:						List[str]=1_0	,  __UpperCAmelCase					:						Optional[int]=None	,  )						->    Tuple:
         """simple docstring"""



         UpperCAmelCase__								=  parent
         UpperCAmelCase__								=  batch_size
         UpperCAmelCase__								=  num_channels
         UpperCAmelCase__								=  image_size
         UpperCAmelCase__								=  depth_multiplier
         UpperCAmelCase__								=  min_depth
         UpperCAmelCase__								=  tf_padding
         UpperCAmelCase__								=  int(last_hidden_size * depth_multiplier		)
         UpperCAmelCase__								=  output_stride
         UpperCAmelCase__								=  hidden_act
         UpperCAmelCase__								=  classifier_dropout_prob
         UpperCAmelCase__								=  use_labels
         UpperCAmelCase__								=  is_training
         UpperCAmelCase__								=  num_labels
         UpperCAmelCase__								=  initializer_range
         UpperCAmelCase__								=  scope


   def       lowercase_				(self					:						List[Any]		)						->    Optional[int]:
         """simple docstring"""



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

         UpperCAmelCase__								=  None
         UpperCAmelCase__								=  None
         if self.use_labels:
               UpperCAmelCase__								=  ids_tensor([self.batch_size]	,  self.num_labels		)
               UpperCAmelCase__								=  ids_tensor([self.batch_size, self.image_size, self.image_size]	,  self.num_labels		)

         UpperCAmelCase__								=  self.get_config()

         return config, pixel_values, labels, pixel_labels


   def       lowercase_				(self					:						List[str]		)						->    Union[str, 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       lowercase_				(self					:						List[str]	,  __UpperCAmelCase					:						Dict	,  __UpperCAmelCase					:						int	,  __UpperCAmelCase					:						str	,  __UpperCAmelCase					:						int		)						->    Any:
         """simple docstring"""



         UpperCAmelCase__								=  MobileNetVaModel(config=__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()
         UpperCAmelCase__								=  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       lowercase_				(self					:						int	,  __UpperCAmelCase					:						Tuple	,  __UpperCAmelCase					:						Optional[Any]	,  __UpperCAmelCase					:						Any	,  __UpperCAmelCase					:						str		)						->    List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  self.num_labels
         UpperCAmelCase__								=  MobileNetVaForImageClassification(__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()
         UpperCAmelCase__								=  model(__UpperCAmelCase	,  labels=__UpperCAmelCase		)
         self.parent.assertEqual(result.logits.shape	,  (self.batch_size, self.num_labels)		)





   def       lowercase_				(self					:						Optional[Any]		)						->    List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  self.prepare_config_and_inputs()
         UpperCAmelCase__		,				UpperCAmelCase__		,				UpperCAmelCase__		,				UpperCAmelCase__								=  config_and_inputs
         UpperCAmelCase__								=  {"pixel_values": pixel_values}
         return config, inputs_dict





@require_torch
class 					A							(    UpperCAmelCase_		,    UpperCAmelCase_		,    unittest.TestCase					):
   __UpperCAmelCase			:			List[Any]              =      (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
   __UpperCAmelCase			:			Optional[int]              =      (
       {'feature-extraction': MobileNetVaModel, 'image-classification': MobileNetVaForImageClassification}
       if is_torch_available()
       else {}
   )

   __UpperCAmelCase			:			Optional[int]              =      False
   __UpperCAmelCase			:			Tuple              =      False
   __UpperCAmelCase			:			str              =      False
   __UpperCAmelCase			:			Dict              =      False


   def       lowercase_				(self					:						Optional[int]		)						->    Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  MobileNetVaModelTester(self		)
         UpperCAmelCase__								=  MobileNetVaConfigTester(self	,  config_class=__UpperCAmelCase	,  has_text_modality=__UpperCAmelCase		)


   def       lowercase_				(self					:						int		)						->    List[str]:
         """simple docstring"""



         self.config_tester.run_common_tests()


   @unittest.skip(reason="MobileNetV1 does not use inputs_embeds"		)
   def       lowercase_				(self					:						Optional[int]		)						->    int:
         """simple docstring"""



         pass


   @unittest.skip(reason="MobileNetV1 does not support input and output embeddings"		)
   def       lowercase_				(self					:						Union[str, Any]		)						->    int:
         """simple docstring"""



         pass


   @unittest.skip(reason="MobileNetV1 does not output attentions"		)
   def       lowercase_				(self					:						int		)						->    str:
         """simple docstring"""



         pass


   def       lowercase_				(self					:						List[str]		)						->    Dict:
         """simple docstring"""



         UpperCAmelCase__		,				UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs_for_common()

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

               UpperCAmelCase__								=  ["pixel_values"]
               self.assertListEqual(arg_names[:1]	,  __UpperCAmelCase		)


   def       lowercase_				(self					:						str		)						->    Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__UpperCAmelCase		)


   def       lowercase_				(self					:						int		)						->    List[str]:
         """simple docstring"""



         def check_hidden_states_output(__UpperCAmelCase					:						Any	,  __UpperCAmelCase					:						Any	,  __UpperCAmelCase					:						List[Any]		):
               UpperCAmelCase__								=  model_class(__UpperCAmelCase		)
               model.to(__UpperCAmelCase		)
               model.eval()

               with torch.no_grad():
                     UpperCAmelCase__								=  model(**self._prepare_for_class(__UpperCAmelCase	,  __UpperCAmelCase		)		)

               UpperCAmelCase__								=  outputs.hidden_states

               UpperCAmelCase__								=  2_6
               self.assertEqual(len(__UpperCAmelCase		)	,  __UpperCAmelCase		)

         UpperCAmelCase__		,				UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
               UpperCAmelCase__								=  True
               check_hidden_states_output(__UpperCAmelCase	,  __UpperCAmelCase	,  __UpperCAmelCase		)

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               UpperCAmelCase__								=  True

               check_hidden_states_output(__UpperCAmelCase	,  __UpperCAmelCase	,  __UpperCAmelCase		)


   def       lowercase_				(self					:						int		)						->    Tuple:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase		)





   @slow
   def       lowercase_				(self					:						Tuple		)						->    Optional[Any]:
         """simple docstring"""



         for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase__								=  MobileNetVaModel.from_pretrained(__UpperCAmelCase		)
               self.assertIsNotNone(__UpperCAmelCase		)




def        lowerCAmelCase_			(					)					->    Optional[Any]:







      '''simple docstring'''


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







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


   @cached_property
   def       lowercase_				(self					:						Optional[Any]		)						->    str:
         """simple docstring"""



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





   @slow
   def       lowercase_				(self					:						Tuple		)						->    int:
         """simple docstring"""



         UpperCAmelCase__								=  MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224"		).to(__UpperCAmelCase		)

         UpperCAmelCase__								=  self.default_image_processor
         UpperCAmelCase__								=  prepare_img()
         UpperCAmelCase__								=  image_processor(images=__UpperCAmelCase	,  return_tensors="pt"		).to(__UpperCAmelCase		)

         # forward pass
         with torch.no_grad():
               UpperCAmelCase__								=  model(**__UpperCAmelCase		)

         # verify the logits
         UpperCAmelCase__								=  torch.Size((1, 1_0_0_1)		)
         self.assertEqual(outputs.logits.shape	,  __UpperCAmelCase		)

         UpperCAmelCase__								=  torch.tensor([-4.1739, -1.1233, 3.1205]		).to(__UpperCAmelCase		)

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




# Lint as: python3
import itertools
import os
import re


UpperCamelCase__    							= re.compile(R'([A-Z]+)([A-Z][a-z])')
UpperCamelCase__    							= re.compile(R'([a-z\d])([A-Z])')

UpperCamelCase__    							= re.compile(R'(?<!_)_(?!_)')
UpperCamelCase__    							= re.compile(R'(_{2,})')

UpperCamelCase__    							= R'^\w+(\.\w+)*$'

UpperCamelCase__    							= R'<>:/\|?*'




def        lowerCAmelCase_			(					__A							)					->    Dict:







      '''simple docstring'''


      UpperCAmelCase__								=  _uppercase_uppercase_re.sub(r"\1_\2",  __A							)
      UpperCAmelCase__								=  _lowercase_uppercase_re.sub(r"\1_\2",  __A							)
      return name.lower()




def        lowerCAmelCase_			(					__A							)					->    Optional[Any]:







      '''simple docstring'''


      UpperCAmelCase__								=  _single_underscore_re.split(__A							)
      UpperCAmelCase__								=  [_multiple_underscores_re.split(__A							) for n in name]
      return "".join(n.capitalize() for n in itertools.chain.from_iterable(__A							) if n != ""							)




def        lowerCAmelCase_			(					__A							)					->    List[str]:







      '''simple docstring'''


      if os.path.basename(__A							) != name:
            raise ValueError(f"""Should be a dataset name, not a path: {name}"""							)
      return camelcase_to_snakecase(__A							)




def        lowerCAmelCase_			(					__A,  __A							)					->    Optional[int]:







      '''simple docstring'''


      if os.path.basename(__A							) != name:
            raise ValueError(f"""Should be a dataset name, not a path: {name}"""							)
      if not re.match(_split_re,  __A							):
            raise ValueError(f"""Split name should match '{_split_re}'' but got '{split}'."""							)
      return f"""{filename_prefix_for_name(__A							)}-{split}"""




def        lowerCAmelCase_			(					__A,  __A,  __A,  __A=None							)					->    str:







      '''simple docstring'''


      UpperCAmelCase__								=  filename_prefix_for_split(__A,  __A							)
      if filetype_suffix:
            prefix += f""".{filetype_suffix}"""
      UpperCAmelCase__								=  os.path.join(__A,  __A							)
      return f"""{filepath}*"""







def        lowerCAmelCase_			(					__A,  __A,  __A,  __A=None,  __A=None							)					->    Any:







      '''simple docstring'''


      UpperCAmelCase__								=  filename_prefix_for_split(__A,  __A							)
      UpperCAmelCase__								=  os.path.join(__A,  __A							)

      if shard_lengths:
            UpperCAmelCase__								=  len(__A							)
            UpperCAmelCase__								=  [f"""{prefix}-{shard_id:05d}-of-{num_shards:05d}""" for shard_id in range(__A							)]
            if filetype_suffix:
                  UpperCAmelCase__								=  [filename + f""".{filetype_suffix}""" for filename in filenames]
            return filenames
      else:
            UpperCAmelCase__								=  prefix
            if filetype_suffix:
                  filename += f""".{filetype_suffix}"""
            return [filename]



