




'''simple docstring'''



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, MobileNetVaForSemanticSegmentation, MobileNetVaModel
      from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import MobileNetVaImageProcessor






class 							_a				(			UpperCAmelCase__ ):





       '''simple docstring'''






       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						self.config_class(**self.inputs_dict  )
             self.parent.assertTrue(hasattr(lowerCamelCase__,							'tf_padding'  )  )
             self.parent.assertTrue(hasattr(lowerCamelCase__,							'depth_multiplier'  )  )






class 							_a				:





       '''simple docstring'''






       def __init__(      self,							A,							A=13,							A=3,							A=32,							A=0.25,							A=8,							A=8,							A=6,							A=32,							A=True,							A=True,							A=True,							A="relu6",							A=1_280,							A=0.1,							A=0.02,							A=True,							A=True,							A=10,							A=None,							):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Any    					=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						None
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						None
             if self.use_labels:
                   SCREAMING_SNAKE_CASE   :      List[str]    					=						ids_tensor([self.batch_size],							self.num_labels  )
                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						ids_tensor([self.batch_size, self.image_size, self.image_size],							self.num_labels  )

             SCREAMING_SNAKE_CASE   :      int    					=						self.get_config()

             return config, pixel_values, labels, pixel_labels







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return MobileNetVaConfig(
                 num_channels=self.num_channels,							image_size=self.image_size,							depth_multiplier=self.depth_multiplier,							depth_divisible_by=self.depth_divisible_by,							min_depth=self.min_depth,							expand_ratio=self.expand_ratio,							output_stride=self.output_stride,							first_layer_is_expansion=self.first_layer_is_expansion,							finegrained_output=self.finegrained_output,							hidden_act=self.hidden_act,							tf_padding=self.tf_padding,							classifier_dropout_prob=self.classifier_dropout_prob,							initializer_range=self.initializer_range,							)







       def        UpperCamelCase_							(      self,							A,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						MobileNetVaModel(config=lowerCamelCase__  )
             model.to(lowerCamelCase__  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						model(lowerCamelCase__  )
             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,
                 ),							)
             self.parent.assertEqual(
                 result.pooler_output.shape,							(self.batch_size, self.last_hidden_size),							)







       def        UpperCamelCase_							(      self,							A,							A,							A,							A  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self,							A,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Any    					=						self.num_labels
             SCREAMING_SNAKE_CASE   :      Dict    					=						MobileNetVaForSemanticSegmentation(lowerCamelCase__  )
             model.to(lowerCamelCase__  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						model(lowerCamelCase__  )
             self.parent.assertEqual(
                 result.logits.shape,							(
                     self.batch_size,
                     self.num_labels,
                     self.image_size // self.output_stride,
                     self.image_size // self.output_stride,
                 ),							)
             SCREAMING_SNAKE_CASE   :      List[str]    					=						model(lowerCamelCase__,							labels=lowerCamelCase__  )
             self.parent.assertEqual(
                 result.logits.shape,							(
                     self.batch_size,
                     self.num_labels,
                     self.image_size // self.output_stride,
                     self.image_size // self.output_stride,
                 ),							)







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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






@require_torch
class 							_a				(			UpperCAmelCase__ ,      UpperCAmelCase__ ,      unittest.TestCase ):





       '''simple docstring'''






       A						:				Dict        =						(
           (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
           if is_torch_available()
           else ()
       )
       A						:				Optional[int]        =						(
           {
               'feature-extraction': MobileNetVaModel,
               'image-classification': MobileNetVaForImageClassification,
               'image-segmentation': MobileNetVaForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       A						:				List[str]        =						False
       A						:				int        =						False
       A						:				List[str]        =						False
       A						:				List[str]        =						False







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						MobileNetVaModelTester(self  )
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						MobileNetVaConfigTester(self,							config_class=lowerCamelCase__,							has_text_modality=lowerCamelCase__  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             self.config_tester.run_common_tests()







       @unittest.skip(reason='MobileNetV2 does not use inputs_embeds'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       @unittest.skip(reason='MobileNetV2 does not support input and output embeddings'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       @unittest.skip(reason='MobileNetV2 does not output attentions'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						model_class(lowerCamelCase__  )
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						inspect.signature(model.forward  )
                   # signature.parameters is an OrderedDict => so arg_names order is deterministic
                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						[*signature.parameters.keys()]

                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						["pixel_values"]
                   self.assertListEqual(arg_names[:1],							lowerCamelCase__  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowerCamelCase__  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             def check_hidden_states_output(A,							A,							A  ):
                   SCREAMING_SNAKE_CASE   :      Any    					=						model_class(lowerCamelCase__  )
                   model.to(lowerCamelCase__  )
                   model.eval()

                   with torch.no_grad():
                         SCREAMING_SNAKE_CASE   :      Any    					=						model(**self._prepare_for_class(lowerCamelCase__,							lowerCamelCase__  )  )

                   SCREAMING_SNAKE_CASE   :      List[str]    					=						outputs.hidden_states

                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						16
                   self.assertEqual(len(lowerCamelCase__  ),							lowerCamelCase__  )

             SCREAMING_SNAKE_CASE   :      int    					=						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE   :      List[str]    					=						True
                   check_hidden_states_output(lowerCamelCase__,							lowerCamelCase__,							lowerCamelCase__  )

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

                   check_hidden_states_output(lowerCamelCase__,							lowerCamelCase__,							lowerCamelCase__  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[Any]    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase__  )







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   SCREAMING_SNAKE_CASE   :      int    					=						MobileNetVaModel.from_pretrained(lowerCamelCase__  )
                   self.assertIsNotNone(lowerCamelCase__  )




def   lowercase__(			):

      """simple docstring"""






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






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





       '''simple docstring'''






       @cached_property
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return (
                 MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224'  ) if is_vision_available() else None
             )







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Any    					=						MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224'  ).to(lowerCamelCase__  )

             SCREAMING_SNAKE_CASE   :      Tuple    					=						self.default_image_processor
             SCREAMING_SNAKE_CASE   :      Any    					=						prepare_img()
             SCREAMING_SNAKE_CASE   :      int    					=						image_processor(images=lowerCamelCase__,							return_tensors='pt'  ).to(lowerCamelCase__  )

             # forward pass
             with torch.no_grad():
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						model(**lowerCamelCase__  )

             # verify the logits
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						torch.Size((1, 1_001)  )
             self.assertEqual(outputs.logits.shape,							lowerCamelCase__  )

             SCREAMING_SNAKE_CASE   :      Any    					=						torch.tensor([0.24_45, -1.19_93, 0.19_05]  ).to(lowerCamelCase__  )

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







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'  )
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						model.to(lowerCamelCase__  )

             SCREAMING_SNAKE_CASE   :      Tuple    					=						MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'  )

             SCREAMING_SNAKE_CASE   :      Tuple    					=						prepare_img()
             SCREAMING_SNAKE_CASE   :      List[str]    					=						image_processor(images=lowerCamelCase__,							return_tensors='pt'  ).to(lowerCamelCase__  )

             # forward pass
             with torch.no_grad():
                   SCREAMING_SNAKE_CASE   :      str    					=						model(**lowerCamelCase__  )
             SCREAMING_SNAKE_CASE   :      str    					=						outputs.logits

             # verify the logits
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						torch.Size((1, 21, 65, 65)  )
             self.assertEqual(logits.shape,							lowerCamelCase__  )

             SCREAMING_SNAKE_CASE   :      Dict    					=						torch.tensor(
                 [
                     [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]],
                     [[-2.15_95, -2.09_77, -2.37_41], [-2.42_26, -2.30_28, -2.68_35], [-2.78_19, -2.59_91, -2.77_06]],
                     [[4.20_58, 4.83_17, 4.76_38], [4.41_36, 5.03_61, 4.93_83], [4.50_28, 4.96_44, 4.87_34]],
                 ],							device=lowerCamelCase__,							)

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



def 		snake_case__	(		lowercase							,				lowercase					):
   lowerCAmelCase_:							list[list[str]]       =	[[] for _ in range(lowercase					)]
   lowerCAmelCase_:							Optional[Any]       =	key - 1

   if key <= 0:
      raise ValueError("Height of grid can't be 0 or negative"					)
   if key == 1 or len(lowercase					) <= key:
      return input_string

   for position, character in enumerate(lowercase					):
      lowerCAmelCase_:							Optional[Any]       =	position % (lowest * 2)  # puts it in bounds
      lowerCAmelCase_:							Any       =	min(lowercase							,				lowest * 2 - num					)  # creates zigzag pattern
      temp_grid[num].append(lowercase					)
   lowerCAmelCase_:							Optional[int]       =	["".join(lowercase					) for row in temp_grid]
   lowerCAmelCase_:							int       =	"".join(lowercase					)

   return output_string
def 		snake_case__	(		lowercase							,				lowercase					):
   lowerCAmelCase_:							Tuple       =	[]
   lowerCAmelCase_:							str       =	key - 1

   if key <= 0:
      raise ValueError("Height of grid can't be 0 or negative"					)
   if key == 1:
      return input_string

   lowerCAmelCase_:							list[list[str]]       =	[[] for _ in range(lowercase					)]  # generates template
   for position in range(len(lowercase					)					):
      lowerCAmelCase_:							List[str]       =	position % (lowest * 2)  # puts it in bounds
      lowerCAmelCase_:							Optional[int]       =	min(lowercase							,				lowest * 2 - num					)  # creates zigzag pattern
      temp_grid[num].append("*"					)

   lowerCAmelCase_:							Optional[Any]       =	0
   for row in temp_grid:  # fills in the characters
      lowerCAmelCase_:							Tuple       =	input_string[counter : counter + len(lowercase					)]
      grid.append(list(lowercase					)					)
      counter += len(lowercase					)

   lowerCAmelCase_:							int       =	""  # reads as zigzag
   for position in range(len(lowercase					)					):
      lowerCAmelCase_:							str       =	position % (lowest * 2)  # puts it in bounds
      lowerCAmelCase_:							Optional[int]       =	min(lowercase							,				lowest * 2 - num					)  # creates zigzag pattern
      output_string += grid[num][0]
      grid[num].pop(0					)
   return output_string
def 		snake_case__	(		lowercase					):
   lowerCAmelCase_:							Dict       =	{}
   for key_guess in range(1							,				len(lowercase					)					):  # tries every key
      lowerCAmelCase_:							int       =	decrypt(lowercase							,				lowercase					)
   return results


if __name__ == "__main__":
 import doctest

 doctest.testmod()