


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 _lowerCamelCase(		_a  ):
       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           _lowercase			:				List[str] 						=						self.config_class(**self.inputs_dict)
           self.parent.assertTrue(hasattr(lowerCamelCase, 'tf_padding'))
           self.parent.assertTrue(hasattr(lowerCamelCase, 'depth_multiplier'))






class _lowerCamelCase:
       def __init__(   self, lowerCamelCase, lowerCamelCase=13, lowerCamelCase=3, lowerCamelCase=32, lowerCamelCase=0.2_5, lowerCamelCase=8, lowerCamelCase=True, lowerCamelCase=10_24, lowerCamelCase=32, lowerCamelCase="relu6", lowerCamelCase=0.1, lowerCamelCase=0.0_2, lowerCamelCase=True, lowerCamelCase=True, lowerCamelCase=10, lowerCamelCase=None, )			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						parent
           _lowercase			:				Any 						=						batch_size
           _lowercase			:				Dict 						=						num_channels
           _lowercase			:				Dict 						=						image_size
           _lowercase			:				List[str] 						=						depth_multiplier
           _lowercase			:				Tuple 						=						min_depth
           _lowercase			:				Union[str, Any] 						=						tf_padding
           _lowercase			:				Optional[int] 						=						int(last_hidden_size * depth_multiplier)
           _lowercase			:				Tuple 						=						output_stride
           _lowercase			:				Optional[Any] 						=						hidden_act
           _lowercase			:				Dict 						=						classifier_dropout_prob
           _lowercase			:				Optional[int] 						=						use_labels
           _lowercase			:				Optional[Any] 						=						is_training
           _lowercase			:				int 						=						num_labels
           _lowercase			:				Tuple 						=						initializer_range
           _lowercase			:				int 						=						scope
       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           _lowercase			:				List[Any] 						=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

           _lowercase			:				str 						=						None
           _lowercase			:				Tuple 						=						None
           if self.use_labels:
               _lowercase			:				Optional[Any] 						=						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      UpperCamelCase	(   self)			->  str:




           """simple docstring"""

           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      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Tuple:




           """simple docstring"""

           _lowercase			:				Dict 						=						MobileNetVaModel(config=lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase			:				List[Any] 						=						model(lowerCamelCase)
           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      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  Union[str, Any]:




           """simple docstring"""

           _lowercase			:				List[str] 						=						self.num_labels
           _lowercase			:				str 						=						MobileNetVaForImageClassification(lowerCamelCase)
           model.to(lowerCamelCase)
           model.eval()
           _lowercase			:				List[Any] 						=						model(lowerCamelCase, labels=lowerCamelCase)
           self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))




       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				Dict 						=						self.prepare_config_and_inputs()
           _lowercase						,							_lowercase						,							_lowercase						,							_lowercase			:				Tuple 						=						config_and_inputs
           _lowercase			:				Optional[Any] 						=						{'pixel_values': pixel_values}
           return config, inputs_dict






@require_torch
class _lowerCamelCase(		_a,					_a,					unittest.TestCase  ):
       lowercase_					:      int       					=     (MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
       lowercase_					:      Union[str, Any]       					=     (
           {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
           if is_torch_available()
           else {}
       )

       lowercase_					:      Dict       					=     False
       lowercase_					:      Optional[Any]       					=     False
       lowercase_					:      Any       					=     False
       lowercase_					:      List[str]       					=     False
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Any 						=						MobileNetVaModelTester(self)
           _lowercase			:				Optional[Any] 						=						MobileNetVaConfigTester(self, config_class=lowerCamelCase, has_text_modality=lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Any:




           """simple docstring"""

           self.config_tester.run_common_tests()
       @unittest.skip(reason='MobileNetV1 does not use inputs_embeds')
       def      UpperCamelCase	(   self)			->  Optional[int]:




           """simple docstring"""

           pass
       @unittest.skip(reason='MobileNetV1 does not support input and output embeddings')
       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

           pass
       @unittest.skip(reason='MobileNetV1 does not output attentions')
       def      UpperCamelCase	(   self)			->  Optional[int]:




           """simple docstring"""

           pass
       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

           _lowercase						,							_lowercase			:				Dict 						=						self.model_tester.prepare_config_and_inputs_for_common()

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

               _lowercase			:				Any 						=						['pixel_values']
               self.assertListEqual(arg_names[:1], lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Dict:




           """simple docstring"""

           _lowercase			:				Tuple 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase)
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           def check_hidden_states_output(lowerCamelCase, lowerCamelCase, lowerCamelCase):
               _lowercase			:				Any 						=						model_class(lowerCamelCase)
               model.to(lowerCamelCase)
               model.eval()

               with torch.no_grad():
                   _lowercase			:				Any 						=						model(**self._prepare_for_class(lowerCamelCase, lowerCamelCase))

               _lowercase			:				List[Any] 						=						outputs.hidden_states

               _lowercase			:				Optional[Any] 						=						26
               self.assertEqual(len(lowerCamelCase), lowerCamelCase)

           _lowercase						,							_lowercase			:				Any 						=						self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               _lowercase			:				Dict 						=						True
               check_hidden_states_output(lowerCamelCase, lowerCamelCase, lowerCamelCase)

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

               check_hidden_states_output(lowerCamelCase, lowerCamelCase, lowerCamelCase)
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowerCamelCase)




       @slow
       def      UpperCamelCase	(   self)			->  str:




           """simple docstring"""

           for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _lowercase			:				str 						=						MobileNetVaModel.from_pretrained(lowerCamelCase)
               self.assertIsNotNone(lowerCamelCase)



def 							UpperCamelCase_( )       ->		Tuple:
    _lowercase			:				int 						=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
    return image






@require_torch
@require_vision
class _lowerCamelCase(		unittest.TestCase  ):
       @cached_property
       def      UpperCamelCase	(   self)			->  List[str]:




           """simple docstring"""

           return (
               MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v1_1.0_224') if is_vision_available() else None
           )




       @slow
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				List[Any] 						=						MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v1_1.0_224').to(lowerCamelCase)

           _lowercase			:				List[str] 						=						self.default_image_processor
           _lowercase			:				Union[str, Any] 						=						prepare_img()
           _lowercase			:				Tuple 						=						image_processor(images=lowerCamelCase, return_tensors='pt').to(lowerCamelCase)

           # forward pass
           with torch.no_grad():
               _lowercase			:				Tuple 						=						model(**lowerCamelCase)

           # verify the logits
           _lowercase			:				Tuple 						=						torch.Size((1, 10_01))
           self.assertEqual(outputs.logits.shape, lowerCamelCase)

           _lowercase			:				List[Any] 						=						torch.tensor([-4.1_7_3_9, -1.1_2_3_3, 3.1_2_0_5]).to(lowerCamelCase)

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









from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_lowerCamelCase      							=   {
    'configuration_clipseg': [
        'CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'CLIPSegConfig',
        'CLIPSegTextConfig',
        'CLIPSegVisionConfig',
    ],
    'processing_clipseg': ['CLIPSegProcessor'],
}

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       _lowerCamelCase      							=   [
           'CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST',
           'CLIPSegModel',
           'CLIPSegPreTrainedModel',
           'CLIPSegTextModel',
           'CLIPSegVisionModel',
           'CLIPSegForImageSegmentation',
       ]

if TYPE_CHECKING:
       from .configuration_clipseg import (
           CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP,
           CLIPSegConfig,
           CLIPSegTextConfig,
           CLIPSegVisionConfig,
       )
       from .processing_clipseg import CLIPSegProcessor

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_clipseg import (
                  CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST,
                  CLIPSegForImageSegmentation,
                  CLIPSegModel,
                  CLIPSegPreTrainedModel,
                  CLIPSegTextModel,
                  CLIPSegVisionModel,
              )

else:
       import sys

       _lowerCamelCase      							=   _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)

