



'''simple docstring'''





import inspect
import unittest

from transformers import MobileViTConfig
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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
       from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import MobileViTImageProcessor







class        UpperCAmelCase_			(			_a      ):
    """simple docstring"""







    def lowerCamelCase			(       self   :	str		):
          snake_case__    :       Dict       		= 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_			:
    """simple docstring"""







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




    def lowerCamelCase			(       self   :	Optional[int]		):
          snake_case__    :       Union[str, Any]       		= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

          snake_case__    :       Tuple       		= self.get_config()

          return config, pixel_values, labels, pixel_labels




    def lowerCamelCase			(       self   :	Optional[Any]		):
          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   :	Tuple					,	snake_case_   :	Any					,	snake_case_   :	Optional[Any]					,	snake_case_   :	List[str]					,	snake_case_   :	Dict		):
          snake_case__    :       Dict       		= MobileViTModel(config=snake_case_		)
          model.to(snake_case_		)
          model.eval()
          snake_case__    :       Optional[Any]       		= model(snake_case_		)
          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 lowerCamelCase			(       self   :	Optional[Any]					,	snake_case_   :	Tuple					,	snake_case_   :	List[Any]					,	snake_case_   :	str					,	snake_case_   :	List[str]		):
          snake_case__    :       Tuple       		= self.num_labels
          snake_case__    :       str       		= MobileViTForImageClassification(snake_case_		)
          model.to(snake_case_		)
          model.eval()
          snake_case__    :       Union[str, Any]       		= model(snake_case_					,	labels=snake_case_		)
          self.parent.assertEqual(result.logits.shape					,	(self.batch_size, self.num_labels)		)




    def lowerCamelCase			(       self   :	List[Any]					,	snake_case_   :	Optional[int]					,	snake_case_   :	List[Any]					,	snake_case_   :	List[str]					,	snake_case_   :	int		):
          snake_case__    :       Dict       		= self.num_labels
          snake_case__    :       Tuple       		= MobileViTForSemanticSegmentation(snake_case_		)
          model.to(snake_case_		)
          model.eval()
          snake_case__    :       List[str]       		= model(snake_case_		)
          self.parent.assertEqual(
              result.logits.shape					,	(
                  self.batch_size,
                  self.num_labels,
                  self.image_size // self.output_stride,
                  self.image_size // self.output_stride,
              )					,	)
          snake_case__    :       int       		= model(snake_case_					,	labels=snake_case_		)
          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 lowerCamelCase			(       self   :	int		):
          snake_case__    :       str       		= self.prepare_config_and_inputs()
          snake_case__		,							snake_case__		,							snake_case__		,							snake_case__    :       int       		= config_and_inputs
          snake_case__    :       Any       		= {"""pixel_values""": pixel_values}
          return config, inputs_dict







@require_torch
class        UpperCAmelCase_			(			_a						,						_a						,						unittest.TestCase      ):
    """simple docstring"""







    lowercase   =						(
        (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
        if is_torch_available()
        else ()
    )
    lowercase   =						(
        {
            "feature-extraction": MobileViTModel,
            "image-classification": MobileViTForImageClassification,
            "image-segmentation": MobileViTForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    lowercase   =						False
    lowercase   =						False
    lowercase   =						False
    lowercase   =						False




    def lowerCamelCase			(       self   :	int		):
          snake_case__    :       List[Any]       		= MobileViTModelTester(self		)
          snake_case__    :       Any       		= MobileViTConfigTester(self					,	config_class=snake_case_					,	has_text_modality=snake_case_		)




    def lowerCamelCase			(       self   :	List[str]		):
          self.config_tester.run_common_tests()




    @unittest.skip(reason="""MobileViT does not use inputs_embeds"""		)
    def lowerCamelCase			(       self   :	Optional[Any]		):
          pass




    @unittest.skip(reason="""MobileViT does not support input and output embeddings"""		)
    def lowerCamelCase			(       self   :	int		):
          pass




    @unittest.skip(reason="""MobileViT does not output attentions"""		)
    def lowerCamelCase			(       self   :	Any		):
          pass




    def lowerCamelCase			(       self   :	Optional[Any]		):
          snake_case__		,							snake_case__    :       Optional[Any]       		= self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                snake_case__    :       int       		= model_class(snake_case_		)
                snake_case__    :       List[str]       		= inspect.signature(model.forward		)
                # signature.parameters is an OrderedDict => so arg_names order is deterministic
                snake_case__    :       List[Any]       		= [*signature.parameters.keys()]

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




    @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""		)
    def lowerCamelCase			(       self   :	Tuple		):
          pass




    def lowerCamelCase			(       self   :	Any		):
          snake_case__    :       List[Any]       		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case_		)




    def lowerCamelCase			(       self   :	Any		):
          def check_hidden_states_output(snake_case_   :	Optional[Any]					,	snake_case_   :	int					,	snake_case_   :	Dict		):
                snake_case__    :       Tuple       		= model_class(snake_case_		)
                model.to(snake_case_		)
                model.eval()

                with torch.no_grad():
                      snake_case__    :       Optional[Any]       		= model(**self._prepare_for_class(snake_case_					,	snake_case_		)		)

                snake_case__    :       Optional[Any]       		= outputs.hidden_states

                snake_case__    :       List[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__    :       Optional[int]       		= 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__    :       List[str]       		= self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                snake_case__    :       Optional[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__    :       Tuple       		= True

                check_hidden_states_output(snake_case_					,	snake_case_					,	snake_case_		)




    def lowerCamelCase			(       self   :	Optional[Any]		):
          snake_case__    :       Optional[int]       		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case_		)




    def lowerCamelCase			(       self   :	Union[str, Any]		):
          snake_case__    :       Optional[Any]       		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*snake_case_		)




    @slow
    def lowerCamelCase			(       self   :	int		):
          for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                snake_case__    :       Tuple       		= MobileViTModel.from_pretrained(snake_case_		)
                self.assertIsNotNone(snake_case_		)





def 		__snake_case(							)						->					Tuple:
      snake_case__    :       int       		= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
      return image







@require_torch
@require_vision
class        UpperCAmelCase_			(			unittest.TestCase      ):
    """simple docstring"""







    @cached_property
    def lowerCamelCase			(       self   :	List[Any]		):
          return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small"""		) if is_vision_available() else None




    @slow
    def lowerCamelCase			(       self   :	List[str]		):
          snake_case__    :       Union[str, Any]       		= MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""		).to(snake_case_		)

          snake_case__    :       Any       		= self.default_image_processor
          snake_case__    :       Union[str, Any]       		= prepare_img()
          snake_case__    :       List[str]       		= image_processor(images=snake_case_					,	return_tensors="""pt"""		).to(snake_case_		)

          # forward pass
          with torch.no_grad():
                snake_case__    :       Dict       		= model(**snake_case_		)

          # verify the logits
          snake_case__    :       List[str]       		= torch.Size((1, 1_000)		)
          self.assertEqual(outputs.logits.shape					,	snake_case_		)

          snake_case__    :       Optional[int]       		= torch.tensor([-1.9364, -1.2327, -0.4653]		).to(snake_case_		)

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




    @slow
    def lowerCamelCase			(       self   :	Optional[int]		):
          snake_case__    :       str       		= MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""		)
          snake_case__    :       Optional[Any]       		= model.to(snake_case_		)

          snake_case__    :       Any       		= MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""		)

          snake_case__    :       Union[str, Any]       		= prepare_img()
          snake_case__    :       Optional[int]       		= image_processor(images=snake_case_					,	return_tensors="""pt"""		).to(snake_case_		)

          # forward pass
          with torch.no_grad():
                snake_case__    :       Tuple       		= model(**snake_case_		)
          snake_case__    :       Optional[int]       		= outputs.logits

          # verify the logits
          snake_case__    :       int       		= torch.Size((1, 21, 32, 32)		)
          self.assertEqual(logits.shape					,	snake_case_		)

          snake_case__    :       Dict       		= torch.tensor(
              [
                  [[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]],
              ]					,	device=snake_case_					,	)

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




    @slow
    def lowerCamelCase			(       self   :	Optional[int]		):
          snake_case__    :       Dict       		= MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""		)
          snake_case__    :       int       		= model.to(snake_case_		)

          snake_case__    :       List[Any]       		= MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""		)

          snake_case__    :       Optional[Any]       		= prepare_img()
          snake_case__    :       List[str]       		= image_processor(images=snake_case_					,	return_tensors="""pt"""		).to(snake_case_		)

          # forward pass
          with torch.no_grad():
                snake_case__    :       Dict       		= model(**snake_case_		)

          snake_case__    :       List[str]       		= outputs.logits.detach().cpu()

          snake_case__    :       Optional[Any]       		= image_processor.post_process_semantic_segmentation(outputs=snake_case_					,	target_sizes=[(50, 60)]		)
          snake_case__    :       List[str]       		= torch.Size((50, 60)		)
          self.assertEqual(segmentation[0].shape					,	snake_case_		)

          snake_case__    :       List[Any]       		= image_processor.post_process_semantic_segmentation(outputs=snake_case_		)
          snake_case__    :       str       		= torch.Size((32, 32)		)
          self.assertEqual(segmentation[0].shape					,	snake_case_		)





'''simple docstring'''





import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar







class        UpperCAmelCase_			(			unittest.TestCase      ):
    """simple docstring"""







    def lowerCamelCase			(       self   :	Optional[int]		):
          snake_case__    :       int       		= logging.get_logger()

          # the current default level is logging.WARNING
          snake_case__    :       str       		= logging.get_verbosity()

          logging.set_verbosity_error()
          self.assertEqual(logger.getEffectiveLevel()					,	logging.get_verbosity()		)

          logging.set_verbosity_warning()
          self.assertEqual(logger.getEffectiveLevel()					,	logging.get_verbosity()		)

          logging.set_verbosity_info()
          self.assertEqual(logger.getEffectiveLevel()					,	logging.get_verbosity()		)

          logging.set_verbosity_debug()
          self.assertEqual(logger.getEffectiveLevel()					,	logging.get_verbosity()		)

          # restore to the original level
          logging.set_verbosity(snake_case_		)




    def lowerCamelCase			(       self   :	Union[str, Any]		):
          snake_case__    :       List[Any]       		= logging.get_verbosity()

          snake_case__    :       Any       		= logging.get_logger("""transformers.models.bart.tokenization_bart"""		)
          snake_case__    :       int       		= """Testing 1, 2, 3"""

          # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
          if level_origin <= logging.WARNING:
                with CaptureLogger(snake_case_		) as cl:
                      logger.warning(snake_case_		)
                self.assertEqual(cl.out					,	msg + """\n"""		)

          # this is setting the level for all of `transformers.*` loggers
          logging.set_verbosity_error()

          # should not be able to log warnings
          with CaptureLogger(snake_case_		) as cl:
                logger.warning(snake_case_		)
          self.assertEqual(cl.out					,	""""""		)

          # should be able to log warnings again
          logging.set_verbosity_warning()
          with CaptureLogger(snake_case_		) as cl:
                logger.warning(snake_case_		)
          self.assertEqual(cl.out					,	msg + """\n"""		)

          # restore to the original level
          logging.set_verbosity(snake_case_		)




    @mockenv(TRANSFORMERS_VERBOSITY="""error"""		)
    def lowerCamelCase			(       self   :	Any		):
          # reset for the env var to take effect, next time some logger call is made
          transformers.utils.logging._reset_library_root_logger()
          # this action activates the env var
          snake_case__    :       Union[str, Any]       		= logging.get_logger("""transformers.models.bart.tokenization_bart"""		)

          snake_case__    :       int       		= os.getenv("""TRANSFORMERS_VERBOSITY"""					,	snake_case_		)
          snake_case__    :       List[Any]       		= logging.log_levels[env_level_str]

          snake_case__    :       str       		= logging.get_verbosity()
          self.assertEqual(
              snake_case_					,	snake_case_					,	f"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}"					,	)

          # restore to the original level
          snake_case__    :       List[Any]       		= """"""
          transformers.utils.logging._reset_library_root_logger()




    @mockenv(TRANSFORMERS_VERBOSITY="""super-error"""		)
    def lowerCamelCase			(       self   :	int		):
          # reset for the env var to take effect, next time some logger call is made
          transformers.utils.logging._reset_library_root_logger()
          snake_case__    :       List[Any]       		= logging.logging.getLogger()
          with CaptureLogger(snake_case_		) as cl:
                # this action activates the env var
                logging.get_logger("""transformers.models.bart.tokenization_bart"""		)
          self.assertIn("""Unknown option TRANSFORMERS_VERBOSITY=super-error"""					,	cl.out		)

          # no need to restore as nothing was changed




    def lowerCamelCase			(       self   :	int		):
          # testing `logger.warning_advice()`
          transformers.utils.logging._reset_library_root_logger()

          snake_case__    :       Optional[int]       		= logging.get_logger("""transformers.models.bart.tokenization_bart"""		)
          snake_case__    :       Tuple       		= """Testing 1, 2, 3"""

          with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="""1"""		):
                # nothing should be logged as env var disables this method
                with CaptureLogger(snake_case_		) as cl:
                      logger.warning_advice(snake_case_		)
                self.assertEqual(cl.out					,	""""""		)

          with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=""""""		):
                # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
                with CaptureLogger(snake_case_		) as cl:
                      logger.warning_advice(snake_case_		)
                self.assertEqual(cl.out					,	msg + """\n"""		)





def 		__snake_case(							)						->					List[str]:
      disable_progress_bar()
      assert are_progress_bars_disabled()

      enable_progress_bar()
      assert not are_progress_bars_disabled()
