

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       SCREAMING_SNAKE_CASE__					(__snake_case     ):





    def       snake_case_				(      self):
         lowercase__    :   Optional[Any]      =       self.config_class(**self.inputs_dict)
         self.parent.assertTrue(hasattr(a						,   'tf_padding'))
         self.parent.assertTrue(hasattr(a						,   'depth_multiplier'))



class       SCREAMING_SNAKE_CASE__					:





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





    def       snake_case_				(      self):
         lowercase__    :   int      =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

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

         return config, pixel_values, labels, pixel_labels





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





    def       snake_case_				(      self						,   a						,   a						,   a						,   a):
         lowercase__    :   List[str]      =       self.num_labels
         lowercase__    :   Tuple      =       MobileNetVaForSemanticSegmentation(a)
         model.to(a)
         model.eval()
         lowercase__    :   List[Any]      =       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__    :   str      =       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       snake_case_				(      self):
         lowercase__    :   List[Any]      =       self.prepare_config_and_inputs()
         lowercase__      , lowercase__      , lowercase__      , lowercase__    :   Dict      =       config_and_inputs
         lowercase__    :   Any      =       {'pixel_values': pixel_values}
         return config, inputs_dict



@require_torch
class       SCREAMING_SNAKE_CASE__					(__snake_case		,       __snake_case		,       unittest.TestCase     ):
    __lowerCamelCase						:       Tuple														=     (
        (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
        if is_torch_available()
        else ()
    )
    __lowerCamelCase						:       Dict														=     (
        {
            """feature-extraction""": MobileNetVaModel,
            """image-classification""": MobileNetVaForImageClassification,
            """image-segmentation""": MobileNetVaForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    __lowerCamelCase						:       Union[str, Any]														=     False
    __lowerCamelCase						:       List[Any]														=     False
    __lowerCamelCase						:       Optional[int]														=     False
    __lowerCamelCase						:       Union[str, Any]														=     False





    def       snake_case_				(      self):
         lowercase__    :   Optional[Any]      =       MobileNetVaModelTester(self)
         lowercase__    :   Optional[int]      =       MobileNetVaConfigTester(self						,   config_class=a						,   has_text_modality=a)





    def       snake_case_				(      self):
         self.config_tester.run_common_tests()





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





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





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





    def       snake_case_				(      self):
         lowercase__      , lowercase__    :   Union[str, Any]      =       self.model_tester.prepare_config_and_inputs_for_common()

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

              lowercase__    :   Union[str, Any]      =       ['pixel_values']
              self.assertListEqual(arg_names[:1]						,   a)





    def       snake_case_				(      self):
         lowercase__    :   int      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*a)





    def       snake_case_				(      self):
         def check_hidden_states_output(a						,   a						,   a):
              lowercase__    :   Dict      =       model_class(a)
              model.to(a)
              model.eval()

              with torch.no_grad():
                   lowercase__    :   List[Any]      =       model(**self._prepare_for_class(a						,   a))

              lowercase__    :   Union[str, Any]      =       outputs.hidden_states

              lowercase__    :   Any      =       16
              self.assertEqual(len(a)						,   a)

         lowercase__      , lowercase__    :   Union[str, Any]      =       self.model_tester.prepare_config_and_inputs_for_common()

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

              check_hidden_states_output(a						,   a						,   a)





    def       snake_case_				(      self):
         lowercase__    :   List[str]      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*a)





    def       snake_case_				(      self):
         lowercase__    :   Optional[Any]      =       self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_semantic_segmentation(*a)





    @slow
    def       snake_case_				(      self):
         for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              lowercase__    :   Optional[Any]      =       MobileNetVaModel.from_pretrained(a)
              self.assertIsNotNone(a)



def 	snake_case__			(    ):



     '''simple docstring'''





     lowercase__    :   Optional[int]      =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
     return image


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





    @cached_property
    def       snake_case_				(      self):
         return (
             MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224') if is_vision_available() else None
         )





    @slow
    def       snake_case_				(      self):
         lowercase__    :   List[Any]      =       MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224').to(a)

         lowercase__    :   Tuple      =       self.default_image_processor
         lowercase__    :   Any      =       prepare_img()
         lowercase__    :   Optional[int]      =       image_processor(images=a						,   return_tensors='pt').to(a)

         # forward pass
         with torch.no_grad():
              lowercase__    :   Dict      =       model(**a)

         # verify the logits
         lowercase__    :   List[str]      =       torch.Size((1, 1001))
         self.assertEqual(outputs.logits.shape						,   a)

         lowercase__    :   Union[str, Any]      =       torch.tensor([0.2_445, -1.1_993, 0.1_905]).to(a)

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





    @slow
    def       snake_case_				(      self):
         lowercase__    :   Tuple      =       MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513')
         lowercase__    :   Optional[int]      =       model.to(a)

         lowercase__    :   Optional[int]      =       MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513')

         lowercase__    :   Tuple      =       prepare_img()
         lowercase__    :   Tuple      =       image_processor(images=a						,   return_tensors='pt').to(a)

         # forward pass
         with torch.no_grad():
              lowercase__    :   List[Any]      =       model(**a)
         lowercase__    :   int      =       outputs.logits

         # verify the logits
         lowercase__    :   str      =       torch.Size((1, 21, 65, 65))
         self.assertEqual(logits.shape						,   a)

         lowercase__    :   str      =       torch.tensor(
             [
                 [[17.5_790, 17.7_581, 18.3_355], [18.3_257, 18.4_230, 18.8_973], [18.6_169, 18.8_650, 19.2_187]],
                 [[-2.1_595, -2.0_977, -2.3_741], [-2.4_226, -2.3_028, -2.6_835], [-2.7_819, -2.5_991, -2.7_706]],
                 [[4.2_058, 4.8_317, 4.7_638], [4.4_136, 5.0_361, 4.9_383], [4.5_028, 4.9_644, 4.8_734]],
             ]						,   device=a						,   )

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




def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    str = "The quick brown fox jumps over the lazy dog"	,     ):



     '''simple docstring'''





     lowercase__    :   str      =       set()

     # Replace all the whitespace in our sentence
     lowercase__    :   Tuple      =       input_str.replace(' '	,     ''			)
     for alpha in input_str:
          if "a" <= alpha.lower() <= "z":
               frequency.add(alpha.lower()			)
     return len(SCREAMING_SNAKE_CASE_			) == 26

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    str = "The quick brown fox jumps over the lazy dog"	,     ):



     '''simple docstring'''





     lowercase__    :   Dict      =       [False] * 26
     for char in input_str:
          if char.islower():
               lowercase__    :   List[Any]      =       True
          elif char.isupper():
               lowercase__    :   Optional[Any]      =       True
     return all(SCREAMING_SNAKE_CASE_			)

def 	snake_case__			(    SCREAMING_SNAKE_CASE_		:    str = "The quick brown fox jumps over the lazy dog"	,     ):



     '''simple docstring'''





     return len({char for char in input_str.lower() if char.isalpha()}			) == 26

def 	snake_case__			(    ):



     '''simple docstring'''





     from timeit import timeit

     lowercase__    :   Union[str, Any]      =       'from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest'
     print(timeit('is_pangram()'	,     setup=SCREAMING_SNAKE_CASE_			)			)
     print(timeit('is_pangram_faster()'	,     setup=SCREAMING_SNAKE_CASE_			)			)
     print(timeit('is_pangram_fastest()'	,     setup=SCREAMING_SNAKE_CASE_			)			)
     # 5.348480500048026, 2.6477354579837993, 1.8470395830227062
     # 5.036091582966037, 2.644472333951853,  1.8869528750656173


if __name__ == "__main__":
       import doctest

       doctest.testmod()
       benchmark()

