
"""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__		( a_		):
   def      __magic_name__     (     self							):
          lowercase       :							Union[str, Any]									=				self.config_class(**self.inputs_dict							)
          self.parent.assertTrue(hasattr(_a      ,       "tf_padding"							)							)
          self.parent.assertTrue(hasattr(_a      ,       "depth_multiplier"							)							)


class 						a__		:
   def __init__(     self      ,       _a      ,       _a=13      ,       _a=3      ,       _a=32      ,       _a=0.2_5      ,       _a=8      ,       _a=8      ,       _a=6      ,       _a=32      ,       _a=True      ,       _a=True      ,       _a=True      ,       _a="relu6"      ,       _a=1_280      ,       _a=0.1      ,       _a=0.0_2      ,       _a=True      ,       _a=True      ,       _a=10      ,       _a=None      ,       ):
          lowercase       :							int									=				parent
          lowercase       :							Optional[int]									=				batch_size
          lowercase       :							Tuple									=				num_channels
          lowercase       :							Optional[Any]									=				image_size
          lowercase       :							List[Any]									=				depth_multiplier
          lowercase       :							str									=				depth_divisible_by
          lowercase       :							Union[str, Any]									=				min_depth
          lowercase       :							Dict									=				expand_ratio
          lowercase       :							Tuple									=				tf_padding
          lowercase       :							List[Any]									=				output_stride
          lowercase       :							Optional[Any]									=				first_layer_is_expansion
          lowercase       :							Optional[Any]									=				finegrained_output
          lowercase       :							List[str]									=				hidden_act
          lowercase       :							List[Any]									=				last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier							)
          lowercase       :							List[str]									=				classifier_dropout_prob
          lowercase       :							List[str]									=				use_labels
          lowercase       :							str									=				is_training
          lowercase       :							Optional[Any]									=				num_labels
          lowercase       :							int									=				initializer_range
          lowercase       :							List[str]									=				scope
   def      __magic_name__     (     self							):
          lowercase       :							List[Any]									=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

          lowercase       :							Any									=				self.get_config()

          return config, pixel_values, labels, pixel_labels
   def      __magic_name__     (     self							):
          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      __magic_name__     (     self      ,       _a      ,       _a      ,       _a      ,       _a							):
          lowercase       :							Optional[int]									=				MobileNetVaModel(config=_a							)
          model.to(_a							)
          model.eval()
          lowercase       :							Dict									=				model(_a							)
          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      __magic_name__     (     self      ,       _a      ,       _a      ,       _a      ,       _a							):
          lowercase       :							Optional[Any]									=				self.num_labels
          lowercase       :							str									=				MobileNetVaForImageClassification(_a							)
          model.to(_a							)
          model.eval()
          lowercase       :							Any									=				model(_a      ,       labels=_a							)
          self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.num_labels)							)
   def      __magic_name__     (     self      ,       _a      ,       _a      ,       _a      ,       _a							):
          lowercase       :							str									=				self.num_labels
          lowercase       :							Any									=				MobileNetVaForSemanticSegmentation(_a							)
          model.to(_a							)
          model.eval()
          lowercase       :							Dict									=				model(_a							)
          self.parent.assertEqual(
              result.logits.shape      ,       (
                  self.batch_size,
                  self.num_labels,
                  self.image_size // self.output_stride,
                  self.image_size // self.output_stride,
              )      ,       )
          lowercase       :							Tuple									=				model(_a      ,       labels=_a							)
          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      __magic_name__     (     self							):
          lowercase       :							Dict									=				self.prepare_config_and_inputs()
          lowercase						,       lowercase						,       lowercase						,       lowercase       :							Dict									=				config_and_inputs
          lowercase       :							Tuple									=				{"pixel_values": pixel_values}
          return config, inputs_dict


@require_torch
class 						a__		( a_,     a_,     unittest.TestCase		):
   __lowerCAmelCase				=							(
       (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
       if is_torch_available()
       else ()
   )
   __lowerCAmelCase				=							(
       {
           """feature-extraction""": MobileNetVaModel,
           """image-classification""": MobileNetVaForImageClassification,
           """image-segmentation""": MobileNetVaForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   __lowerCAmelCase				=							False
   __lowerCAmelCase				=							False
   __lowerCAmelCase				=							False
   __lowerCAmelCase				=							False
   def      __magic_name__     (     self							):
          lowercase       :							Tuple									=				MobileNetVaModelTester(self							)
          lowercase       :							List[Any]									=				MobileNetVaConfigTester(self      ,       config_class=_a      ,       has_text_modality=_a							)
   def      __magic_name__     (     self							):
          self.config_tester.run_common_tests()
   @unittest.skip(reason="MobileNetV2 does not use inputs_embeds"							)
   def      __magic_name__     (     self							):
          pass
   @unittest.skip(reason="MobileNetV2 does not support input and output embeddings"							)
   def      __magic_name__     (     self							):
          pass
   @unittest.skip(reason="MobileNetV2 does not output attentions"							)
   def      __magic_name__     (     self							):
          pass
   def      __magic_name__     (     self							):
          lowercase						,       lowercase       :							Union[str, Any]									=				self.model_tester.prepare_config_and_inputs_for_common()

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

                 lowercase       :							List[str]									=				["pixel_values"]
                 self.assertListEqual(arg_names[:1]      ,       _a							)
   def      __magic_name__     (     self							):
          lowercase       :							Tuple									=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_a							)
   def      __magic_name__     (     self							):
          def check_hidden_states_output(_a      ,       _a      ,       _a							):
                 lowercase       :							Optional[Any]									=				model_class(_a							)
                 model.to(_a							)
                 model.eval()

                 with torch.no_grad():
                        lowercase       :							int									=				model(**self._prepare_for_class(_a      ,       _a							)							)

                 lowercase       :							int									=				outputs.hidden_states

                 lowercase       :							int									=				16
                 self.assertEqual(len(_a							)      ,       _a							)

          lowercase						,       lowercase       :							List[str]									=				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 lowercase       :							List[Any]									=				True
                 check_hidden_states_output(_a      ,       _a      ,       _a							)

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

                 check_hidden_states_output(_a      ,       _a      ,       _a							)
   def      __magic_name__     (     self							):
          lowercase       :							Tuple									=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_a							)
   def      __magic_name__     (     self							):
          lowercase       :							List[Any]									=				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*_a							)

   @slow
   def      __magic_name__     (     self							):
          for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 lowercase       :							Optional[Any]									=				MobileNetVaModel.from_pretrained(_a							)
                 self.assertIsNotNone(_a							)


def     __magic_name__      ( )					->							Dict:
       lowercase       :							Optional[int]									=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
       return image

@require_torch
@require_vision
class 						a__		( unittest.TestCase		):
   @cached_property
   def      __magic_name__     (     self							):
          return (
              MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224"							) if is_vision_available() else None
          )
   @slow
   def      __magic_name__     (     self							):
          lowercase       :							Union[str, Any]									=				MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"							).to(_a							)

          lowercase       :							Union[str, Any]									=				self.default_image_processor
          lowercase       :							Tuple									=				prepare_img()
          lowercase       :							Tuple									=				image_processor(images=_a      ,       return_tensors="pt"							).to(_a							)

          # forward pass
          with torch.no_grad():
                 lowercase       :							Optional[int]									=				model(**_a							)

          # verify the logits
          lowercase       :							Any									=				torch.Size((1, 1_001)							)
          self.assertEqual(outputs.logits.shape      ,       _a							)

          lowercase       :							Any									=				torch.tensor([0.2_4_4_5, -1.1_9_9_3, 0.1_9_0_5]							).to(_a							)

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

   @slow
   def      __magic_name__     (     self							):
          lowercase       :							List[str]									=				MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"							)
          lowercase       :							int									=				model.to(_a							)

          lowercase       :							List[Any]									=				MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"							)

          lowercase       :							str									=				prepare_img()
          lowercase       :							Union[str, Any]									=				image_processor(images=_a      ,       return_tensors="pt"							).to(_a							)

          # forward pass
          with torch.no_grad():
                 lowercase       :							str									=				model(**_a							)
          lowercase       :							List[str]									=				outputs.logits

          # verify the logits
          lowercase       :							Dict									=				torch.Size((1, 21, 65, 65)							)
          self.assertEqual(logits.shape      ,       _a							)

          lowercase       :							Any									=				torch.tensor(
              [
                  [[1_7.5_7_9_0, 1_7.7_5_8_1, 1_8.3_3_5_5], [1_8.3_2_5_7, 1_8.4_2_3_0, 1_8.8_9_7_3], [1_8.6_1_6_9, 1_8.8_6_5_0, 1_9.2_1_8_7]],
                  [[-2.1_5_9_5, -2.0_9_7_7, -2.3_7_4_1], [-2.4_2_2_6, -2.3_0_2_8, -2.6_8_3_5], [-2.7_8_1_9, -2.5_9_9_1, -2.7_7_0_6]],
                  [[4.2_0_5_8, 4.8_3_1_7, 4.7_6_3_8], [4.4_1_3_6, 5.0_3_6_1, 4.9_3_8_3], [4.5_0_2_8, 4.9_6_4_4, 4.8_7_3_4]],
              ]      ,       device=_a      ,       )

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




"""simple docstring"""




import builtins
import sys

from ...utils.imports import _is_package_available
from . import cursor, input
from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
from .keymap import KEYMAP


_A     :			str  						=			False
try:
   _A     :			Dict  						=			_is_package_available("""google.colab""")
except ModuleNotFoundError:
   pass

@input.register
class 						a__		:
   def __init__(     self      ,       _a = None      ,       _a = []							):
          lowercase       :							Union[str, Any]									=				0
          lowercase       :							str									=				choices
          lowercase       :							List[Any]									=				prompt
          if sys.platform == "win32":
                 lowercase       :							Union[str, Any]									=				"*"
          else:
                 lowercase       :							int									=				"➔ "
   def      __magic_name__     (     self      ,       _a      ,       _a = ""							):
          if sys.platform != "win32":
                 writeColor(self.choices[index]      ,       32      ,       _a							)
          else:
                 forceWrite(self.choices[index]      ,       _a							)
   def      __magic_name__     (     self      ,       _a							):
          if index == self.position:
                 forceWrite(f""" {self.arrow_char} """							)
                 self.write_choice(_a							)
          else:
                 forceWrite(f"""    {self.choices[index]}"""							)
          reset_cursor()
   def      __magic_name__     (     self      ,       _a      ,       _a = 1							):
          lowercase       :							Optional[int]									=				self.position
          if direction == Direction.DOWN:
                 if self.position + 1 >= len(self.choices							):
                        return
                 self.position += num_spaces
          else:
                 if self.position - 1 < 0:
                        return
                 self.position -= num_spaces
          clear_line()
          self.print_choice(_a							)
          move_cursor(_a      ,       direction.name							)
          self.print_choice(self.position							)
   @input.mark(KEYMAP["up"]							)
   def      __magic_name__     (     self							):
          self.move_direction(Direction.UP							)
   @input.mark(KEYMAP["down"]							)
   def      __magic_name__     (     self							):
          self.move_direction(Direction.DOWN							)
   @input.mark(KEYMAP["newline"]							)
   def      __magic_name__     (     self							):
          move_cursor(len(self.choices							) - self.position      ,       "DOWN"							)
          return self.position
   @input.mark(KEYMAP["interrupt"]							)
   def      __magic_name__     (     self							):
          move_cursor(len(self.choices							) - self.position      ,       "DOWN"							)
          raise KeyboardInterrupt
   @input.mark_multiple(*[KEYMAP[str(_a							)] for number in range(10							)]							)
   def      __magic_name__     (     self							):
          lowercase       :							List[str]									=				int(chr(self.current_selection							)							)
          lowercase       :							Union[str, Any]									=				index - self.position
          if index == self.position:
                 return
          if index < len(self.choices							):
                 if self.position > index:
                        self.move_direction(Direction.UP      ,       -movement							)
                 elif self.position < index:
                        self.move_direction(Direction.DOWN      ,       _a							)
                 else:
                        return
          else:
                 return

   def      __magic_name__     (     self      ,       _a = 0							):
          if self.prompt:
                 linebreak()
                 forceWrite(self.prompt      ,       "\n"							)
                 if in_colab:
                        forceWrite("Please input a choice index (starting from 0), and press enter"      ,       "\n"							)
                 else:
                        forceWrite("Please select a choice using the arrow or number keys, and selecting with enter"      ,       "\n"							)
          lowercase       :							Tuple									=				default_choice
          for i in range(len(self.choices							)							):
                 self.print_choice(_a							)
                 forceWrite("\n"							)
          move_cursor(len(self.choices							) - self.position      ,       "UP"							)
          with cursor.hide():
                 while True:
                        if in_colab:
                               try:
                                      lowercase       :							Tuple									=				int(builtins.input()							)
                               except ValueError:
                                      lowercase       :							Optional[int]									=				default_choice
                        else:
                               lowercase       :							int									=				self.handle_input()
                        if choice is not None:
                               reset_cursor()
                               for _ in range(len(self.choices							) + 1							):
                                      move_cursor(1      ,       "UP"							)
                                      clear_line()
                               self.write_choice(_a      ,       "\n"							)
                               return choice


