


"""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, 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  (  _a  ):







    """simple docstring"""




    def      __snake_case							( self    :   Union[str, Any]):
      a						:		int											=      self.config_class(**self.inputs_dict)
      self.parent.assertTrue(hasattr(__UpperCAmelCase    ,			"tf_padding"))
      self.parent.assertTrue(hasattr(__UpperCAmelCase    ,			"depth_multiplier"))






class 						_A  :







    """simple docstring"""




    def __init__( self    :   int    ,			__UpperCAmelCase    :   Optional[int]    ,			__UpperCAmelCase    :   List[Any]=13    ,			__UpperCAmelCase    :   str=3    ,			__UpperCAmelCase    :   Optional[int]=32    ,			__UpperCAmelCase    :   Dict=0.25    ,			__UpperCAmelCase    :   int=8    ,			__UpperCAmelCase    :   int=True    ,			__UpperCAmelCase    :   Optional[int]=1024    ,			__UpperCAmelCase    :   Dict=32    ,			__UpperCAmelCase    :   Union[str, Any]="relu6"    ,			__UpperCAmelCase    :   Any=0.1    ,			__UpperCAmelCase    :   Union[str, Any]=0.02    ,			__UpperCAmelCase    :   List[str]=True    ,			__UpperCAmelCase    :   Union[str, Any]=True    ,			__UpperCAmelCase    :   str=10    ,			__UpperCAmelCase    :   List[Any]=None    ,			):
      a						:		Any											=      parent
      a						:		int											=      batch_size
      a						:		Any											=      num_channels
      a						:		Optional[Any]											=      image_size
      a						:		int											=      depth_multiplier
      a						:		Tuple											=      min_depth
      a						:		Any											=      tf_padding
      a						:		Union[str, Any]											=      int(last_hidden_size * depth_multiplier)
      a						:		Optional[int]											=      output_stride
      a						:		int											=      hidden_act
      a						:		Dict											=      classifier_dropout_prob
      a						:		str											=      use_labels
      a						:		List[Any]											=      is_training
      a						:		str											=      num_labels
      a						:		Optional[int]											=      initializer_range
      a						:		Tuple											=      scope






    def      __snake_case							( self    :   int):
      a						:		Optional[int]											=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

      a						:		Any											=      None
      a						:		Tuple											=      None
      if self.use_labels:
        a						:		List[Any]											=      ids_tensor([self.batch_size]    ,			self.num_labels)
        a						:		Dict											=      ids_tensor([self.batch_size, self.image_size, self.image_size]    ,			self.num_labels)

      a						:		Union[str, Any]											=      self.get_config()

      return config, pixel_values, labels, pixel_labels






    def      __snake_case							( self    :   Any):
      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      __snake_case							( self    :   int    ,			__UpperCAmelCase    :   Optional[Any]    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   Dict):
      a						:		List[Any]											=      MobileNetVaModel(config=__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		Dict											=      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      __snake_case							( self    :   Optional[Any]    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   List[str]    ,			__UpperCAmelCase    :   Tuple):
      a						:		Any											=      self.num_labels
      a						:		Union[str, Any]											=      MobileNetVaForImageClassification(__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		List[str]											=      model(__UpperCAmelCase    ,			labels=__UpperCAmelCase)
      self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels))






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






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







    """simple docstring"""




    UpperCAmelCase	:							List[str]     =	(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
    UpperCAmelCase	:							int     =	(
        {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
        if is_torch_available()
        else {}
    )

    UpperCAmelCase	:							Dict     =	False
    UpperCAmelCase	:							Dict     =	False
    UpperCAmelCase	:							Tuple     =	False
    UpperCAmelCase	:							Optional[int]     =	False






    def      __snake_case							( self    :   Any):
      a						:		int											=      MobileNetVaModelTester(self)
      a						:		List[str]											=      MobileNetVaConfigTester(self    ,			config_class=__UpperCAmelCase    ,			has_text_modality=__UpperCAmelCase)






    def      __snake_case							( self    :   List[Any]):
      self.config_tester.run_common_tests()






    @unittest.skip(reason="MobileNetV1 does not use inputs_embeds")
    def      __snake_case							( self    :   Optional[int]):
      pass






    @unittest.skip(reason="MobileNetV1 does not support input and output embeddings")
    def      __snake_case							( self    :   str):
      pass






    @unittest.skip(reason="MobileNetV1 does not output attentions")
    def      __snake_case							( self    :   Union[str, Any]):
      pass






    def      __snake_case							( self    :   int):
      a						:		Optional[Any]											=      self.model_tester.prepare_config_and_inputs_for_common()

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

        a						:		Optional[Any]											=      ["pixel_values"]
        self.assertListEqual(arg_names[:1]    ,			__UpperCAmelCase)






    def      __snake_case							( self    :   Union[str, Any]):
      a						:		int											=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase)






    def      __snake_case							( self    :   int):
      def check_hidden_states_output(__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   Optional[Any]):
        a						:		List[str]											=      model_class(__UpperCAmelCase)
        model.to(__UpperCAmelCase)
        model.eval()

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

        a						:		Optional[int]											=      outputs.hidden_states

        a						:		Any											=      26
        self.assertEqual(len(__UpperCAmelCase)    ,			__UpperCAmelCase)

      a						:		Optional[int]											=      self.model_tester.prepare_config_and_inputs_for_common()

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

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

        check_hidden_states_output(__UpperCAmelCase    ,			__UpperCAmelCase    ,			__UpperCAmelCase)






    def      __snake_case							( self    :   int):
      a						:		List[Any]											=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase)






    @slow
    def      __snake_case							( self    :   Optional[Any]):
      for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a						:		Tuple											=      MobileNetVaModel.from_pretrained(__UpperCAmelCase)
        self.assertIsNotNone(__UpperCAmelCase)






def 					lowercase      (    )->				Tuple:
  '''simple docstring'''







  a						:		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      __snake_case							( self    :   int):
      return (
          MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224") if is_vision_available() else None
      )






    @slow
    def      __snake_case							( self    :   Dict):
      a						:		Any											=      MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224").to(__UpperCAmelCase)

      a						:		Union[str, Any]											=      self.default_image_processor
      a						:		Optional[int]											=      prepare_img()
      a						:		List[Any]											=      image_processor(images=__UpperCAmelCase    ,			return_tensors="pt").to(__UpperCAmelCase)

      # forward pass
      with torch.no_grad():
        a						:		Union[str, Any]											=      model(**__UpperCAmelCase)

      # verify the logits
      a						:		Tuple											=      torch.Size((1, 1001))
      self.assertEqual(outputs.logits.shape    ,			__UpperCAmelCase)

      a						:		List[str]											=      torch.tensor([-4.1_739, -1.1_233, 3.1_205]).to(__UpperCAmelCase)

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










"""simple docstring"""







import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
 import torch






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase	:							str     =	"""char"""
    UpperCAmelCase	:							Optional[Any]     =	"""bpe"""
    UpperCAmelCase	:							Optional[Any]     =	"""wp"""






__lowercase    =				(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)






class 						_A  (  _a  ):







    """simple docstring"""




    UpperCAmelCase	:							Optional[Any]     =	["""image_processor""", """char_tokenizer"""]
    UpperCAmelCase	:							Optional[Any]     =	"""ViTImageProcessor"""
    UpperCAmelCase	:							List[Any]     =	"""MgpstrTokenizer"""






    def __init__( self    :   List[Any]    ,			__UpperCAmelCase    :   Union[str, Any]=None    ,			__UpperCAmelCase    :   Dict=None    ,			**__UpperCAmelCase    :   str):
      a						:		Tuple											=      None
      if "feature_extractor" in kwargs:
        warnings.warn(
            "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
            " instead."    ,			__UpperCAmelCase    ,			)
        a						:		List[str]											=      kwargs.pop("feature_extractor")

      a						:		Dict											=      image_processor if image_processor is not None else feature_extractor
      if image_processor is None:
        raise ValueError("You need to specify an `image_processor`.")
      if tokenizer is None:
        raise ValueError("You need to specify a `tokenizer`.")

      a						:		Union[str, Any]											=      tokenizer
      a						:		int											=      AutoTokenizer.from_pretrained("gpt2")
      a						:		str											=      AutoTokenizer.from_pretrained("bert-base-uncased")

      super().__init__(__UpperCAmelCase    ,			__UpperCAmelCase)






    def __call__( self    :   str    ,			__UpperCAmelCase    :   Dict=None    ,			__UpperCAmelCase    :   Tuple=None    ,			__UpperCAmelCase    :   Union[str, Any]=None    ,			**__UpperCAmelCase    :   int):
      if images is None and text is None:
        raise ValueError("You need to specify either an `images` or `text` input to process.")

      if images is not None:
        a						:		List[str]											=      self.image_processor(__UpperCAmelCase    ,			return_tensors=__UpperCAmelCase    ,			**__UpperCAmelCase)
      if text is not None:
        a						:		Optional[Any]											=      self.char_tokenizer(__UpperCAmelCase    ,			return_tensors=__UpperCAmelCase    ,			**__UpperCAmelCase)

      if text is None:
        return inputs
      elif images is None:
        return encodings
      else:
        a						:		Any											=      encodings["input_ids"]
        return inputs






    def      __snake_case							( self    :   List[Any]    ,			__UpperCAmelCase    :   List[str]):
      a							,		a							,		a						:		Tuple											=      sequences
      a						:		Optional[int]											=      char_preds.size(0)

      a							,		a						:		Dict											=      self._decode_helper(__UpperCAmelCase    ,			"char")
      a							,		a						:		Dict											=      self._decode_helper(__UpperCAmelCase    ,			"bpe")
      a							,		a						:		Union[str, Any]											=      self._decode_helper(__UpperCAmelCase    ,			"wp")

      a						:		Any											=      []
      a						:		Union[str, Any]											=      []
      for i in range(__UpperCAmelCase):
        a						:		Any											=      [char_scores[i], bpe_scores[i], wp_scores[i]]
        a						:		Optional[Any]											=      [char_strs[i], bpe_strs[i], wp_strs[i]]
        a						:		List[str]											=      scores.index(max(__UpperCAmelCase))
        final_strs.append(strs[max_score_index])
        final_scores.append(scores[max_score_index])

      a						:		Dict											=      {}
      a						:		List[str]											=      final_strs
      a						:		str											=      final_scores
      a						:		int											=      char_strs
      a						:		int											=      bpe_strs
      a						:		Tuple											=      wp_strs
      return out






    def      __snake_case							( self    :   Any    ,			__UpperCAmelCase    :   List[str]    ,			__UpperCAmelCase    :   List[str]):
      if format == DecodeType.CHARACTER:
        a						:		int											=      self.char_decode
        a						:		int											=      1
        a						:		Dict											=      "[s]"
      elif format == DecodeType.BPE:
        a						:		List[str]											=      self.bpe_decode
        a						:		List[str]											=      2
        a						:		int											=      "#"
      elif format == DecodeType.WORDPIECE:
        a						:		Union[str, Any]											=      self.wp_decode
        a						:		List[str]											=      102
        a						:		int											=      "[SEP]"
      else:
        raise ValueError(f'''Format {format} is not supported.''')

      a							,		a						:		str											=      [], []
      a						:		Optional[int]											=      pred_logits.size(0)
      a						:		List[str]											=      pred_logits.size(1)
      a							,		a						:		Tuple											=      pred_logits.topk(1    ,			dim=-1    ,			largest=__UpperCAmelCase    ,			sorted=__UpperCAmelCase)
      a						:		List[str]											=      preds_index.view(-1    ,			__UpperCAmelCase)[:, 1:]
      a						:		Any											=      decoder(__UpperCAmelCase)
      a							,		a						:		Union[str, Any]											=      torch.nn.functional.softmax(__UpperCAmelCase    ,			dim=2).max(dim=2)
      a						:		Union[str, Any]											=      preds_max_prob[:, 1:]

      for index in range(__UpperCAmelCase):
        a						:		str											=      preds_str[index].find(__UpperCAmelCase)
        a						:		Optional[Any]											=      preds_str[index][:pred_eos]
        a						:		Optional[int]											=      preds_index[index].cpu().tolist()
        a						:		Optional[int]											=      pred_index.index(__UpperCAmelCase) if eos_token in pred_index else -1
        a						:		List[str]											=      preds_max_prob[index][: pred_eos_index + 1]
        a						:		int											=      pred_max_prob.cumprod(dim=0)[-1] if pred_max_prob.nelement() != 0 else 0.0
        dec_strs.append(__UpperCAmelCase)
        conf_scores.append(__UpperCAmelCase)

      return dec_strs, conf_scores






    def      __snake_case							( self    :   Optional[int]    ,			__UpperCAmelCase    :   Any):
      a						:		Dict											=      [seq.replace(" "    ,			"") for seq in self.char_tokenizer.batch_decode(__UpperCAmelCase)]
      return decode_strs






    def      __snake_case							( self    :   Optional[int]    ,			__UpperCAmelCase    :   List[str]):
      return self.bpe_tokenizer.batch_decode(__UpperCAmelCase)






    def      __snake_case							( self    :   Union[str, Any]    ,			__UpperCAmelCase    :   int):
      a						:		Any											=      [seq.replace(" "    ,			"") for seq in self.wp_tokenizer.batch_decode(__UpperCAmelCase)]
      return decode_strs






