



"""simple docstring"""


import importlib
import inspect
import json
import os
from collections import OrderedDict

# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...image_processing_utils import ImageProcessingMixin
from ...tokenization_utils import TOKENIZER_CONFIG_FILE
from ...utils import FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)
from .feature_extraction_auto import AutoFeatureExtractor
from .image_processing_auto import AutoImageProcessor
from .tokenization_auto import AutoTokenizer


snake_case_								=			logging.get_logger(__name__)

snake_case_								=			OrderedDict(
    [
        ("""align""", """AlignProcessor"""),
        ("""altclip""", """AltCLIPProcessor"""),
        ("""bark""", """BarkProcessor"""),
        ("""blip""", """BlipProcessor"""),
        ("""blip-2""", """Blip2Processor"""),
        ("""bridgetower""", """BridgeTowerProcessor"""),
        ("""chinese_clip""", """ChineseCLIPProcessor"""),
        ("""clap""", """ClapProcessor"""),
        ("""clip""", """CLIPProcessor"""),
        ("""clipseg""", """CLIPSegProcessor"""),
        ("""flava""", """FlavaProcessor"""),
        ("""git""", """GitProcessor"""),
        ("""groupvit""", """CLIPProcessor"""),
        ("""hubert""", """Wav2Vec2Processor"""),
        ("""instructblip""", """InstructBlipProcessor"""),
        ("""layoutlmv2""", """LayoutLMv2Processor"""),
        ("""layoutlmv3""", """LayoutLMv3Processor"""),
        ("""markuplm""", """MarkupLMProcessor"""),
        ("""mctct""", """MCTCTProcessor"""),
        ("""mgp-str""", """MgpstrProcessor"""),
        ("""oneformer""", """OneFormerProcessor"""),
        ("""owlvit""", """OwlViTProcessor"""),
        ("""pix2struct""", """Pix2StructProcessor"""),
        ("""sam""", """SamProcessor"""),
        ("""sew""", """Wav2Vec2Processor"""),
        ("""sew-d""", """Wav2Vec2Processor"""),
        ("""speech_to_text""", """Speech2TextProcessor"""),
        ("""speech_to_text_2""", """Speech2Text2Processor"""),
        ("""speecht5""", """SpeechT5Processor"""),
        ("""trocr""", """TrOCRProcessor"""),
        ("""tvlt""", """TvltProcessor"""),
        ("""unispeech""", """Wav2Vec2Processor"""),
        ("""unispeech-sat""", """Wav2Vec2Processor"""),
        ("""vilt""", """ViltProcessor"""),
        ("""vision-text-dual-encoder""", """VisionTextDualEncoderProcessor"""),
        ("""wav2vec2""", """Wav2Vec2Processor"""),
        ("""wav2vec2-conformer""", """Wav2Vec2Processor"""),
        ("""wavlm""", """Wav2Vec2Processor"""),
        ("""whisper""", """WhisperProcessor"""),
        ("""xclip""", """XCLIPProcessor"""),
    ]
)

snake_case_								=			_LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)

def 					_lowerCAmelCase (  lowercase_		):
						for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
												if class_name in processors:
																		UpperCAmelCase			 =					model_type_to_module_name(lowercase_		)

																		UpperCAmelCase			 =					importlib.import_module(F""".{module_name}"""						,      'transformers.models'		)
																		try:
																								return getattr(lowercase_						,      lowercase_		)
																		except AttributeError:
																								continue

						for processor in PROCESSOR_MAPPING._extra_content.values():
												if getattr(lowercase_						,      '__name__'						,      lowercase_		) == class_name:
																		return processor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
						UpperCAmelCase			 =					importlib.import_module('transformers'		)
						if hasattr(lowercase_						,      lowercase_		):
												return getattr(lowercase_						,      lowercase_		)

						return None







class  A_     :



						"""simple docstring"""






						def __init__(   self					:Optional[Any]   )							->     str:
												raise EnvironmentError(
												    'AutoProcessor is designed to be instantiated '
												    'using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method.'   )






						@classmethod
						@replace_list_option_in_docstrings(lowercase_   )
						def       UpperCAmelCase__	(   cls					:Optional[int]  ,    lowercase_					:Tuple  ,    **lowercase_					:int   )							->     Optional[int]:
												UpperCAmelCase			 =					kwargs.pop('config'  ,    lowercase_   )
												UpperCAmelCase			 =					kwargs.pop('trust_remote_code'  ,    lowercase_   )
												UpperCAmelCase			 =					True

												UpperCAmelCase			 =					None
												UpperCAmelCase			 =					None

												# First, let's see if we have a preprocessor config.
												# Filter the kwargs for `get_file_from_repo`.
												UpperCAmelCase			 =					{
												    key: kwargs[key] for key in inspect.signature(lowercase_   ).parameters.keys() if key in kwargs
												}
												# Let's start by checking whether the processor class is saved in an image processor
												UpperCAmelCase			 =					get_file_from_repo(
												    lowercase_  ,    lowercase_  ,    **lowercase_   )
												if preprocessor_config_file is not None:
																		UpperCAmelCase ,       UpperCAmelCase			 =					ImageProcessingMixin.get_image_processor_dict(lowercase_  ,    **lowercase_   )
																		UpperCAmelCase			 =					config_dict.get('processor_class'  ,    lowercase_   )
																		if "AutoProcessor" in config_dict.get('auto_map'  ,    {}   ):
																								UpperCAmelCase			 =					config_dict['auto_map']['AutoProcessor']

        # If not found, let's check whether the processor class is saved in a feature extractor config
												if preprocessor_config_file is not None and processor_class is None:
																		UpperCAmelCase ,       UpperCAmelCase			 =					FeatureExtractionMixin.get_feature_extractor_dict(lowercase_  ,    **lowercase_   )
																		UpperCAmelCase			 =					config_dict.get('processor_class'  ,    lowercase_   )
																		if "AutoProcessor" in config_dict.get('auto_map'  ,    {}   ):
																								UpperCAmelCase			 =					config_dict['auto_map']['AutoProcessor']

												if processor_class is None:
																		# Next, let's check whether the processor class is saved in a tokenizer
																		UpperCAmelCase			 =					get_file_from_repo(
																		    lowercase_  ,    lowercase_  ,    **lowercase_   )
																		if tokenizer_config_file is not None:
																								with open(lowercase_  ,    encoding='utf-8'   ) as reader:
																														UpperCAmelCase			 =					json.load(lowercase_   )

																								UpperCAmelCase			 =					config_dict.get('processor_class'  ,    lowercase_   )
																								if "AutoProcessor" in config_dict.get('auto_map'  ,    {}   ):
																														UpperCAmelCase			 =					config_dict['auto_map']['AutoProcessor']

												if processor_class is None:
																		# Otherwise, load config, if it can be loaded.
																		if not isinstance(lowercase_  ,    lowercase_   ):
																								UpperCAmelCase			 =					AutoConfig.from_pretrained(
																								    lowercase_  ,    trust_remote_code=lowercase_  ,    **lowercase_   )

																		# And check if the config contains the processor class.
																		UpperCAmelCase			 =					getattr(lowercase_  ,    'processor_class'  ,    lowercase_   )
																		if hasattr(lowercase_  ,    'auto_map'   ) and "AutoProcessor" in config.auto_map:
																								UpperCAmelCase			 =					config.auto_map['AutoProcessor']

												if processor_class is not None:
																		UpperCAmelCase			 =					processor_class_from_name(lowercase_   )

												UpperCAmelCase			 =					processor_auto_map is not None
												UpperCAmelCase			 =					processor_class is not None or type(lowercase_   ) in PROCESSOR_MAPPING
												UpperCAmelCase			 =					resolve_trust_remote_code(
												    lowercase_  ,    lowercase_  ,    lowercase_  ,    lowercase_   )

												if has_remote_code and trust_remote_code:
																		UpperCAmelCase			 =					get_class_from_dynamic_module(
																		    lowercase_  ,    lowercase_  ,    **lowercase_   )
																		UpperCAmelCase			 =					kwargs.pop('code_revision'  ,    lowercase_   )
																		if os.path.isdir(lowercase_   ):
																								processor_class.register_for_auto_class()
																		return processor_class.from_pretrained(
																		    lowercase_  ,    trust_remote_code=lowercase_  ,    **lowercase_   )
												elif processor_class is not None:
																		return processor_class.from_pretrained(
																		    lowercase_  ,    trust_remote_code=lowercase_  ,    **lowercase_   )
												# Last try: we use the PROCESSOR_MAPPING.
												elif type(lowercase_   ) in PROCESSOR_MAPPING:
																		return PROCESSOR_MAPPING[type(lowercase_   )].from_pretrained(lowercase_  ,    **lowercase_   )

												# At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a
												# tokenizer.
												try:
																		return AutoTokenizer.from_pretrained(
																		    lowercase_  ,    trust_remote_code=lowercase_  ,    **lowercase_   )
												except Exception:
																		try:
																								return AutoImageProcessor.from_pretrained(
																								    lowercase_  ,    trust_remote_code=lowercase_  ,    **lowercase_   )
																		except Exception:
																								pass

																		try:
																								return AutoFeatureExtractor.from_pretrained(
																								    lowercase_  ,    trust_remote_code=lowercase_  ,    **lowercase_   )
																		except Exception:
																								pass

												raise ValueError(
												    f"""Unrecognized processing class in {pretrained_model_name_or_path}. Can't instantiate a processor, a """
												    'tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains'
												    'the files of at least one of those processing classes.'   )






						@staticmethod
						def       UpperCAmelCase__	(   lowercase_					:int  ,    lowercase_					:Union[str, Any]   )							->     Tuple:
												PROCESSOR_MAPPING.register(lowercase_  ,    lowercase_   )







"""simple docstring"""
from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import numpy as np
    import tensorflow as tf

    from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
    from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import MobileViTImageProcessor






class   _UpperCAmelCase					(       _snake_case):
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[str]            = self.config_class(**self.inputs_dict  )
      self.parent.assertTrue(hasattr(snake_case_    ,     "hidden_sizes"  )  )
      self.parent.assertTrue(hasattr(snake_case_    ,     "neck_hidden_sizes"  )  )
      self.parent.assertTrue(hasattr(snake_case_    ,     "num_attention_heads"  )  )






class   _UpperCAmelCase					:
    def __init__(     self    ,     snake_case_    ,     snake_case_=13    ,     snake_case_=32    ,     snake_case_=2    ,     snake_case_=3    ,     snake_case_=6_40    ,     snake_case_=4    ,     snake_case_="silu"    ,     snake_case_=3    ,     snake_case_=32    ,     snake_case_=0.1    ,     snake_case_=0.1    ,     snake_case_=0.1    ,     snake_case_=0.02    ,     snake_case_=True    ,     snake_case_=True    ,     snake_case_=10    ,     snake_case_=None    ,     ):
      _snake_case  :    List[Any]            = parent
      _snake_case  :    Union[str, Any]            = batch_size
      _snake_case  :    List[Any]            = image_size
      _snake_case  :    List[Any]            = patch_size
      _snake_case  :    Optional[Any]            = num_channels
      _snake_case  :    List[Any]            = last_hidden_size
      _snake_case  :    Tuple            = num_attention_heads
      _snake_case  :    Any            = hidden_act
      _snake_case  :    List[Any]            = conv_kernel_size
      _snake_case  :    int            = output_stride
      _snake_case  :    Dict            = hidden_dropout_prob
      _snake_case  :    Optional[int]            = attention_probs_dropout_prob
      _snake_case  :    List[Any]            = classifier_dropout_prob
      _snake_case  :    List[str]            = use_labels
      _snake_case  :    Dict            = is_training
      _snake_case  :    List[str]            = num_labels
      _snake_case  :    Optional[Any]            = initializer_range
      _snake_case  :    Dict            = scope
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Optional[int]            = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

      _snake_case  :    Optional[Any]            = self.get_config()

      return config, pixel_values, labels, pixel_labels
    def        lowerCamelCase__						(     self  ):
      return MobileViTConfig(
          image_size=self.image_size    ,     patch_size=self.patch_size    ,     num_channels=self.num_channels    ,     num_attention_heads=self.num_attention_heads    ,     hidden_act=self.hidden_act    ,     conv_kernel_size=self.conv_kernel_size    ,     output_stride=self.output_stride    ,     hidden_dropout_prob=self.hidden_dropout_prob    ,     attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,     classifier_dropout_prob=self.classifier_dropout_prob    ,     initializer_range=self.initializer_range    ,     )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_  ):
      _snake_case  :    str            = TFMobileViTModel(config=snake_case_  )
      _snake_case  :    Optional[int]            = model(snake_case_    ,     training=snake_case_  )
      _snake_case  :    List[Any]            = self.image_size // self.output_stride
      self.parent.assertEqual(
          result.last_hidden_state.shape    ,     (self.batch_size, self.last_hidden_size, expected_height, expected_width)  )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_  ):
      _snake_case  :    int            = self.num_labels
      _snake_case  :    Optional[Any]            = TFMobileViTForImageClassification(snake_case_  )
      _snake_case  :    str            = model(snake_case_    ,     labels=snake_case_    ,     training=snake_case_  )
      self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_labels)  )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_  ):
      _snake_case  :    List[str]            = self.num_labels
      _snake_case  :    Any            = TFMobileViTForSemanticSegmentation(snake_case_  )
      _snake_case  :    Optional[Any]            = self.image_size // self.output_stride

      _snake_case  :    Any            = model(snake_case_    ,     training=snake_case_  )
      self.parent.assertEqual(
          result.logits.shape    ,     (self.batch_size, self.num_labels, expected_height, expected_width)  )

      _snake_case  :    List[Any]            = model(snake_case_    ,     labels=snake_case_    ,     training=snake_case_  )
      self.parent.assertEqual(
          result.logits.shape    ,     (self.batch_size, self.num_labels, expected_height, expected_width)  )


    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Union[str, Any]            = self.prepare_config_and_inputs()
      _snake_case      ,       _snake_case      ,       _snake_case      ,       _snake_case  :    str            = config_and_inputs
      _snake_case  :    Optional[int]            = {"pixel_values": pixel_values}
      return config, inputs_dict






@require_tf
class   _UpperCAmelCase					(       _snake_case		,       _snake_case		,       unittest.TestCase):
    __lowercase				:			Tuple	=       (
        (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
        if is_tf_available()
        else ()
    )
    __lowercase				:			int	=       (
        {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
        if is_tf_available()
        else {}
    )

    __lowercase				:			Optional[int]	=       False
    __lowercase				:			Optional[int]	=       False
    __lowercase				:			List[Any]	=       False
    __lowercase				:			int	=       False
    __lowercase				:			Union[str, Any]	=       False
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Tuple            = TFMobileViTModelTester(self  )
      _snake_case  :    Dict            = TFMobileViTConfigTester(self    ,     config_class=snake_case_    ,     has_text_modality=snake_case_  )
    def        lowerCamelCase__						(     self  ):
      self.config_tester.run_common_tests()
    @unittest.skip(reason="MobileViT does not use inputs_embeds"  )
    def        lowerCamelCase__						(     self  ):
      pass
    @unittest.skip(reason="MobileViT does not support input and output embeddings"  )
    def        lowerCamelCase__						(     self  ):
      pass
    @unittest.skip(reason="MobileViT does not output attentions"  )
    def        lowerCamelCase__						(     self  ):
      pass
    def        lowerCamelCase__						(     self  ):
      _snake_case      ,       _snake_case  :    Optional[int]            = self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        _snake_case  :    List[Any]            = model_class(snake_case_  )
        _snake_case  :    Any            = inspect.signature(model.call  )
        # 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]    ,     snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[Any]            = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*snake_case_  )
    def        lowerCamelCase__						(     self  ):
      def check_hidden_states_output(snake_case_    ,     snake_case_    ,     snake_case_  ):
        _snake_case  :    Optional[int]            = model_class(snake_case_  )

        _snake_case  :    Dict            = model(**self._prepare_for_class(snake_case_    ,     snake_case_  )  )

        _snake_case  :    Optional[Any]            = outputs.hidden_states

        _snake_case  :    Any            = 5
        self.assertEqual(len(snake_case_  )    ,     snake_case_  )

        # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
        # with the width and height being successively divided by 2.
        _snake_case  :    Dict            = 2
        for i in range(len(snake_case_  )  ):
          self.assertListEqual(
              list(hidden_states[i].shape[-2:]  )    ,     [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]    ,     )
          divisor *= 2

        self.assertEqual(self.model_tester.output_stride    ,     divisor // 2  )

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

      for model_class in self.all_model_classes:
        _snake_case  :    Union[str, Any]            = True
        check_hidden_states_output(snake_case_    ,     snake_case_    ,     snake_case_  )

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

        check_hidden_states_output(snake_case_    ,     snake_case_    ,     snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[str]            = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Tuple            = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*snake_case_  )
    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices("GPU"  )  ) == 0    ,     reason="TF does not support backprop for grouped convolutions on CPU."    ,     )
    def        lowerCamelCase__						(     self  ):
      super().test_dataset_conversion()
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_=2E-1    ,     snake_case_=2E-1  ):
      self.assertTrue(np.allclose(snake_case_    ,     snake_case_    ,     atol=snake_case_    ,     rtol=snake_case_  )  )
    @unittest.skipIf(
        not is_tf_available() or len(tf.config.list_physical_devices("GPU"  )  ) == 0    ,     reason="TF does not support backprop for grouped convolutions on CPU."    ,     )
    @slow
    def        lowerCamelCase__						(     self  ):
      _snake_case      ,       _snake_case  :    Optional[int]            = self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        # Since `TFMobileViTModel` cannot operate with the default `fit()` method.
        if model_class.__name__ != "TFMobileViTModel":
          _snake_case  :    List[str]            = model_class(snake_case_  )
          if getattr(snake_case_    ,     "hf_compute_loss"    ,     snake_case_  ):
            super().test_keras_fit()
    def        lowerCamelCase__						(     self  ):
      _snake_case      ,       _snake_case  :    Optional[int]            = self.model_tester.prepare_config_and_inputs_for_common()
      for model_class in self.all_model_classes:
        # set an ignore index to correctly test the masked loss used in
        # `TFMobileViTForSemanticSegmentation`.
        if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
          _snake_case  :    Optional[Any]            = 5

        _snake_case  :    Optional[Any]            = model_class(snake_case_  )
        if getattr(snake_case_    ,     "hf_compute_loss"    ,     snake_case_  ):
          # The number of elements in the loss should be the same as the number of elements in the label
          _snake_case  :    Optional[Any]            = self._prepare_for_class(inputs_dict.copy()    ,     snake_case_    ,     return_labels=snake_case_  )
          _snake_case  :    int            = prepared_for_class[
              sorted(prepared_for_class.keys() - inputs_dict.keys()    ,     reverse=snake_case_  )[0]
          ]
          _snake_case  :    Optional[Any]            = added_label.shape.as_list()[:1]

          # Test that model correctly compute the loss with kwargs
          _snake_case  :    List[str]            = self._prepare_for_class(inputs_dict.copy()    ,     snake_case_    ,     return_labels=snake_case_  )
          _snake_case  :    str            = {"input_ids", "pixel_values", "input_features"}
          _snake_case  :    Optional[int]            = possible_input_names.intersection(set(snake_case_  )  ).pop()
          _snake_case  :    int            = prepared_for_class.pop(snake_case_  )

          _snake_case  :    Union[str, Any]            = model(snake_case_    ,     **snake_case_  )[0]
          self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )

          # Test that model correctly compute the loss when we mask some positions
          _snake_case  :    Optional[Any]            = self._prepare_for_class(inputs_dict.copy()    ,     snake_case_    ,     return_labels=snake_case_  )
          _snake_case  :    Any            = {"input_ids", "pixel_values", "input_features"}
          _snake_case  :    Optional[int]            = possible_input_names.intersection(set(snake_case_  )  ).pop()
          _snake_case  :    List[str]            = prepared_for_class.pop(snake_case_  )
          if "labels" in prepared_for_class:
            _snake_case  :    Optional[int]            = prepared_for_class["labels"].numpy()
            if len(labels.shape  ) > 1 and labels.shape[1] != 1:
              # labels[0] = -100
              _snake_case  :    Optional[int]            = tf.convert_to_tensor(snake_case_  )
              _snake_case  :    Union[str, Any]            = model(snake_case_    ,     **snake_case_  )[0]
              self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )
              self.assertTrue(not np.any(np.isnan(loss.numpy()  )  )  )

                # Test that model correctly compute the loss with a dict
          _snake_case  :    Tuple            = self._prepare_for_class(inputs_dict.copy()    ,     snake_case_    ,     return_labels=snake_case_  )
          _snake_case  :    Tuple            = model(snake_case_  )[0]
          self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )

          # Test that model correctly compute the loss with a tuple
          _snake_case  :    Dict            = self._prepare_for_class(inputs_dict.copy()    ,     snake_case_    ,     return_labels=snake_case_  )

          # Get keys that were added with the _prepare_for_class function
          _snake_case  :    Union[str, Any]            = prepared_for_class.keys() - inputs_dict.keys()
          _snake_case  :    Any            = inspect.signature(model.call  ).parameters
          _snake_case  :    List[Any]            = list(signature.keys()  )

          # Create a dictionary holding the location of the tensors in the tuple
          _snake_case  :    Union[str, Any]            = {0: input_name}
          for label_key in label_keys:
            _snake_case  :    Tuple            = signature_names.index(snake_case_  )
            _snake_case  :    int            = label_key
          _snake_case  :    List[Any]            = sorted(tuple_index_mapping.items()  )
          # Initialize a list with their default values, update the values and convert to a tuple
          _snake_case  :    List[Any]            = []

          for name in signature_names:
            if name != "kwargs":
              list_input.append(signature[name].default  )

          for index, value in sorted_tuple_index_mapping:
            _snake_case  :    int            = prepared_for_class[value]

          _snake_case  :    str            = tuple(snake_case_  )

          # Send to model
          _snake_case  :    Union[str, Any]            = model(tuple_input[:-1]  )[0]

          self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]  )


    @slow
    def        lowerCamelCase__						(     self  ):
      for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _snake_case  :    Optional[int]            = TFMobileViTModel.from_pretrained(snake_case_  )
        self.assertIsNotNone(snake_case_  )


def 					a__ ( ):

  """simple docstring"""







  _snake_case  :    Union[str, Any]            = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
  return image






@require_tf
class   _UpperCAmelCase					(       unittest.TestCase):
    @slow
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Optional[Any]            = TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"  )

      _snake_case  :    List[Any]            = MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small"  )
      _snake_case  :    List[Any]            = prepare_img()
      _snake_case  :    List[str]            = image_processor(images=snake_case_    ,     return_tensors="tf"  )

      # forward pass
      _snake_case  :    Union[str, Any]            = model(**snake_case_    ,     training=snake_case_  )

      # verify the logits
      _snake_case  :    Optional[Any]            = tf.TensorShape((1, 10_00)  )
      self.assertEqual(outputs.logits.shape    ,     snake_case_  )

      _snake_case  :    List[Any]            = tf.constant([-1.9364, -1.2327, -0.4653]  )

      tf.debugging.assert_near(outputs.logits[0, :3]    ,     snake_case_    ,     atol=1E-4    ,     rtol=1E-04  )


    @slow
    def        lowerCamelCase__						(     self  ):
      # `from_pt` will be removed
      _snake_case  :    List[str]            = TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"  )

      _snake_case  :    int            = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small"  )

      _snake_case  :    List[Any]            = prepare_img()
      _snake_case  :    str            = image_processor(images=snake_case_    ,     return_tensors="tf"  )

      # forward pass
      _snake_case  :    Tuple            = model(inputs.pixel_values    ,     training=snake_case_  )
      _snake_case  :    Tuple            = outputs.logits

      # verify the logits
      _snake_case  :    Any            = tf.TensorShape((1, 21, 32, 32)  )
      self.assertEqual(logits.shape    ,     snake_case_  )

      _snake_case  :    str            = tf.constant(
          [
              [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
              [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
              [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
          ]  )

      tf.debugging.assert_near(logits[0, :3, :3, :3]    ,     snake_case_    ,     rtol=1E-4    ,     atol=1E-4  )

