import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch
    from torch import nn

    from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
    from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import DPTImageProcessor






class     __UpperCAmelCase:






 """simple docstring"""




 def __init__(    self ,       __magic_name__ ,       __magic_name__=2 ,       __magic_name__=32 ,       __magic_name__=16 ,       __magic_name__=3 ,       __magic_name__=True ,       __magic_name__=True ,       __magic_name__=32 ,       __magic_name__=4 ,       __magic_name__=[0, 1, 2, 3] ,       __magic_name__=4 ,       __magic_name__=37 ,       __magic_name__="gelu" ,       __magic_name__=0.1 ,       __magic_name__=0.1 ,       __magic_name__=0.02 ,       __magic_name__=3 ,       __magic_name__=False ,       __magic_name__=None ,       ):

        """simple docstring"""

        A_							:       Any	      =				parent
        A_							:       Optional[Any]	      =				batch_size
        A_							:       Dict	      =				image_size
        A_							:       Any	      =				patch_size
        A_							:       Union[str, Any]	      =				num_channels
        A_							:       List[Any]	      =				is_training
        A_							:       Dict	      =				use_labels
        A_							:       Union[str, Any]	      =				hidden_size
        A_							:       int	      =				num_hidden_layers
        A_							:       Optional[Any]	      =				backbone_out_indices
        A_							:       Optional[Any]	      =				num_attention_heads
        A_							:       Optional[Any]	      =				intermediate_size
        A_							:       List[Any]	      =				hidden_act
        A_							:       Tuple	      =				hidden_dropout_prob
        A_							:       Optional[int]	      =				attention_probs_dropout_prob
        A_							:       Dict	      =				initializer_range
        A_							:       Optional[Any]	      =				num_labels
        A_							:       Union[str, Any]	      =				scope
        A_							:       List[Any]	      =				is_hybrid
        # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
        A_							:       Dict	      =				(image_size // patch_size) ** 2
        A_							:       Any	      =				num_patches + 1
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

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

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

        A_							:       List[Any]	      =				self.get_config()

        return config, pixel_values, labels
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        return DPTConfig(
            image_size=self.image_size ,       patch_size=self.patch_size ,       num_channels=self.num_channels ,       hidden_size=self.hidden_size ,       num_hidden_layers=self.num_hidden_layers ,       backbone_out_indices=self.backbone_out_indices ,       num_attention_heads=self.num_attention_heads ,       intermediate_size=self.intermediate_size ,       hidden_act=self.hidden_act ,       hidden_dropout_prob=self.hidden_dropout_prob ,       attention_probs_dropout_prob=self.attention_probs_dropout_prob ,       is_decoder=__magic_name__ ,       initializer_range=self.initializer_range ,       is_hybrid=self.is_hybrid ,       )
 def  UpperCAmelCase   (    self ,       __magic_name__ ,       __magic_name__ ,       __magic_name__      ):

        """simple docstring"""

        A_							:       Tuple	      =				DPTModel(config=__magic_name__      )
        model.to(__magic_name__      )
        model.eval()
        A_							:       Dict	      =				model(__magic_name__      )
        self.parent.assertEqual(result.last_hidden_state.shape ,       (self.batch_size, self.seq_length, self.hidden_size)      )
 def  UpperCAmelCase   (    self ,       __magic_name__ ,       __magic_name__ ,       __magic_name__      ):

        """simple docstring"""

        A_							:       Union[str, Any]	      =				self.num_labels
        A_							:       Optional[Any]	      =				DPTForDepthEstimation(__magic_name__      )
        model.to(__magic_name__      )
        model.eval()
        A_							:       Tuple	      =				model(__magic_name__      )
        self.parent.assertEqual(result.predicted_depth.shape ,       (self.batch_size, self.image_size, self.image_size)      )
 def  UpperCAmelCase   (    self ,       __magic_name__ ,       __magic_name__ ,       __magic_name__      ):

        """simple docstring"""

        A_							:       Dict	      =				self.num_labels
        A_							:       Tuple	      =				DPTForSemanticSegmentation(__magic_name__      )
        model.to(__magic_name__      )
        model.eval()
        A_							:       List[Any]	      =				model(__magic_name__ ,       labels=__magic_name__      )
        self.parent.assertEqual(
            result.logits.shape ,       (self.batch_size, self.num_labels, self.image_size, self.image_size)      )
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

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






@require_torch
class     __UpperCAmelCase(    A__      ,	A__      ,	unittest.TestCase				):






 """simple docstring"""




 __magic_name__          =   (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
 __magic_name__          =   (
     {
         """depth-estimation""": DPTForDepthEstimation,
         """feature-extraction""": DPTModel,
         """image-segmentation""": DPTForSemanticSegmentation,
     }
     if is_torch_available()
     else {}
 )

 __magic_name__          =   False
 __magic_name__          =   False
 __magic_name__          =   False
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        A_							:       List[str]	      =				DPTModelTester(self      )
        A_							:       Any	      =				ConfigTester(self ,       config_class=__magic_name__ ,       has_text_modality=__magic_name__ ,       hidden_size=37      )
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        self.config_tester.run_common_tests()
 @unittest.skip(reason='''DPT does not use inputs_embeds'''      )
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        pass
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

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

        for model_class in self.all_model_classes:
               A_							:       Optional[int]	      =				model_class(__magic_name__      )
               self.assertIsInstance(model.get_input_embeddings() ,       (nn.Module)      )
               A_							:       str	      =				model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(__magic_name__ ,       nn.Linear      )      )
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

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

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

               A_							:       int	      =				['''pixel_values''']
               self.assertListEqual(arg_names[:1] ,       __magic_name__      )
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        A_							:       Any	      =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__magic_name__      )
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        A_							:       Dict	      =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_depth_estimation(*__magic_name__      )
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        A_							:       str	      =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*__magic_name__      )
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        for model_class in self.all_model_classes:
               if model_class.__name__ == "DPTForDepthEstimation":
                      continue

               A_      ,							A_							:       Dict	      =				self.model_tester.prepare_config_and_inputs_for_common()
               A_							:       int	      =				True

               if model_class in get_values(__magic_name__      ):
                      continue

               A_							:       Any	      =				model_class(__magic_name__      )
               model.to(__magic_name__      )
               model.train()
               A_							:       Any	      =				self._prepare_for_class(__magic_name__ ,       __magic_name__ ,       return_labels=__magic_name__      )
               A_							:       List[str]	      =				model(**__magic_name__      ).loss
               loss.backward()
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        for model_class in self.all_model_classes:
               if model_class.__name__ == "DPTForDepthEstimation":
                      continue

               A_      ,							A_							:       str	      =				self.model_tester.prepare_config_and_inputs_for_common()
               A_							:       List[str]	      =				False
               A_							:       int	      =				True

               if model_class in get_values(__magic_name__      ) or not model_class.supports_gradient_checkpointing:
                      continue
               A_							:       Dict	      =				model_class(__magic_name__      )
               model.to(__magic_name__      )
               model.gradient_checkpointing_enable()
               model.train()
               A_							:       Optional[Any]	      =				self._prepare_for_class(__magic_name__ ,       __magic_name__ ,       return_labels=__magic_name__      )
               A_							:       str	      =				model(**__magic_name__      ).loss
               loss.backward()
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        A_      ,							A_							:       Optional[Any]	      =				self.model_tester.prepare_config_and_inputs_for_common()

        A_							:       List[str]	      =				_config_zero_init(__magic_name__      )
        for model_class in self.all_model_classes:
               A_							:       Optional[int]	      =				model_class(config=__magic_name__      )
               # Skip the check for the backbone
               A_							:       str	      =				[]
               for name, module in model.named_modules():
                      if module.__class__.__name__ == "DPTViTHybridEmbeddings":
                             A_							:       Dict	      =				[f"""{name}.{key}""" for key in module.state_dict().keys()]
                             break

               for name, param in model.named_parameters():
                      if param.requires_grad:
                             if name in backbone_params:
                                    continue
                             self.assertIn(
                                 ((param.data.mean() * 1e9).round() / 1e9).item() ,       [0.0, 1.0] ,       msg=f"""Parameter {name} of model {model_class} seems not properly initialized""" ,       )
 @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''      )
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        pass
 @slow
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               A_							:       Tuple	      =				DPTModel.from_pretrained(__magic_name__      )
               self.assertIsNotNone(__magic_name__      )


def       a__      (					)		->	Union[str, Any]:
       A_							:       Union[str, Any]	      =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''							)
       return image






@require_torch
@require_vision
@slow
class     __UpperCAmelCase(    unittest.TestCase				):






 """simple docstring"""




 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        A_							:       Union[str, Any]	      =				DPTImageProcessor.from_pretrained('''Intel/dpt-large'''      )
        A_							:       Optional[Any]	      =				DPTForDepthEstimation.from_pretrained('''Intel/dpt-large'''      ).to(__magic_name__      )

        A_							:       int	      =				prepare_img()
        A_							:       List[str]	      =				image_processor(images=__magic_name__ ,       return_tensors='''pt'''      ).to(__magic_name__      )

        # forward pass
        with torch.no_grad():
               A_							:       str	      =				model(**__magic_name__      )
               A_							:       Optional[int]	      =				outputs.predicted_depth

        # verify the predicted depth
        A_							:       Any	      =				torch.Size((1, 384, 384)      )
        self.assertEqual(predicted_depth.shape ,       __magic_name__      )

        A_							:       Any	      =				torch.tensor(
            [[6.31_99, 6.36_29, 6.41_48], [6.38_50, 6.36_15, 6.41_66], [6.35_19, 6.31_76, 6.35_75]]      ).to(__magic_name__      )

        self.assertTrue(torch.allclose(outputs.predicted_depth[0, :3, :3] ,       __magic_name__ ,       atol=1e-4      )      )
 def  UpperCAmelCase   (    self      ):

        """simple docstring"""

        A_							:       Optional[Any]	      =				DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''      )
        A_							:       List[Any]	      =				DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''      ).to(__magic_name__      )

        A_							:       Dict	      =				prepare_img()
        A_							:       int	      =				image_processor(images=__magic_name__ ,       return_tensors='''pt'''      ).to(__magic_name__      )

        # forward pass
        with torch.no_grad():
               A_							:       Optional[Any]	      =				model(**__magic_name__      )

        # verify the logits
        A_							:       Any	      =				torch.Size((1, 150, 480, 480)      )
        self.assertEqual(outputs.logits.shape ,       __magic_name__      )

        A_							:       Dict	      =				torch.tensor(
            [[4.04_80, 4.24_20, 4.43_60], [4.31_24, 4.56_93, 4.82_61], [4.57_68, 4.89_65, 5.21_63]]      ).to(__magic_name__      )

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

        """simple docstring"""

        A_							:       Any	      =				DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''      )
        A_							:       Union[str, Any]	      =				DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''      ).to(__magic_name__      )

        A_							:       Optional[Any]	      =				prepare_img()
        A_							:       Any	      =				image_processor(images=__magic_name__ ,       return_tensors='''pt'''      ).to(__magic_name__      )

        # forward pass
        with torch.no_grad():
               A_							:       Optional[Any]	      =				model(**__magic_name__      )

        A_							:       List[Any]	      =				outputs.logits.detach().cpu()

        A_							:       List[str]	      =				image_processor.post_process_semantic_segmentation(outputs=__magic_name__ ,       target_sizes=[(500, 300)]      )
        A_							:       str	      =				torch.Size((500, 300)      )
        self.assertEqual(segmentation[0].shape ,       __magic_name__      )

        A_							:       Optional[Any]	      =				image_processor.post_process_semantic_segmentation(outputs=__magic_name__      )
        A_							:       Tuple	      =				torch.Size((480, 480)      )
        self.assertEqual(segmentation[0].shape ,       __magic_name__      )



from transformers import ProcessorMixin






class     __UpperCAmelCase(    A__				):






 """simple docstring"""




 __magic_name__          =   """AutoFeatureExtractor"""
 __magic_name__          =   """AutoTokenizer"""


