




'''simple docstring'''







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 				_a   :





     '''simple docstring'''



     def __init__(							self       ,__a       ,__a=2       ,__a=32       ,__a=16       ,__a=3       ,__a=True       ,__a=True       ,__a=32       ,__a=4       ,__a=[0, 1, 2, 3]       ,__a=4       ,__a=37       ,__a="gelu"       ,__a=0.1       ,__a=0.1       ,__a=0.02       ,__a=3       ,__a=False       ,__a=None       ,)			->							Optional[Any]:
          snake_case :			Optional[Any]					   = parent
          snake_case :			str					   = batch_size
          snake_case :			List[Any]					   = image_size
          snake_case :			Optional[Any]					   = patch_size
          snake_case :			List[str]					   = num_channels
          snake_case :			int					   = is_training
          snake_case :			Optional[int]					   = use_labels
          snake_case :			Tuple					   = hidden_size
          snake_case :			Dict					   = num_hidden_layers
          snake_case :			str					   = backbone_out_indices
          snake_case :			Dict					   = num_attention_heads
          snake_case :			List[Any]					   = intermediate_size
          snake_case :			Dict					   = hidden_act
          snake_case :			str					   = hidden_dropout_prob
          snake_case :			List[str]					   = attention_probs_dropout_prob
          snake_case :			Optional[Any]					   = initializer_range
          snake_case :			Tuple					   = num_labels
          snake_case :			Any					   = scope
          snake_case :			Dict					   = is_hybrid
          # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
          snake_case :			List[str]					   = (image_size // patch_size) ** 2
          snake_case :			str					   = num_patches + 1







     def  snake_case_			(							self       )			->							Optional[int]:
          snake_case :			int					   = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

          snake_case :			Optional[int]					   = None
          if self.use_labels:
               snake_case :			Union[str, Any]					   = 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







     def  snake_case_			(							self       )			->							int:
          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=__a       ,initializer_range=self.initializer_range       ,is_hybrid=self.is_hybrid       ,)







     def  snake_case_			(							self       ,__a       ,__a       ,__a       )			->							List[Any]:
          snake_case :			str					   = DPTModel(config=__a       )
          model.to(__a       )
          model.eval()
          snake_case :			Optional[int]					   = model(__a       )
          self.parent.assertEqual(result.last_hidden_state.shape       ,(self.batch_size, self.seq_length, self.hidden_size)       )







     def  snake_case_			(							self       ,__a       ,__a       ,__a       )			->							List[str]:
          snake_case :			Optional[Any]					   = self.num_labels
          snake_case :			Any					   = DPTForDepthEstimation(__a       )
          model.to(__a       )
          model.eval()
          snake_case :			Any					   = model(__a       )
          self.parent.assertEqual(result.predicted_depth.shape       ,(self.batch_size, self.image_size, self.image_size)       )







     def  snake_case_			(							self       ,__a       ,__a       ,__a       )			->							str:
          snake_case :			str					   = self.num_labels
          snake_case :			int					   = DPTForSemanticSegmentation(__a       )
          model.to(__a       )
          model.eval()
          snake_case :			Optional[Any]					   = model(__a       ,labels=__a       )
          self.parent.assertEqual(
              result.logits.shape       ,(self.batch_size, self.num_labels, self.image_size, self.image_size)       )







     def  snake_case_			(							self       )			->							Tuple:
          snake_case :			str					   = self.prepare_config_and_inputs()
          snake_case   ,		snake_case   ,		snake_case :			Dict					   = config_and_inputs
          snake_case :			int					   = {"""pixel_values""": pixel_values}
          return config, inputs_dict







@require_torch
class 				_a   (a__,		a__,		unittest.TestCase  ):





     '''simple docstring'''



     lowerCAmelCase_     :    Optional[Any]									=				(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
     lowerCAmelCase_     :    List[str]									=				(
         {
             """depth-estimation""": DPTForDepthEstimation,
             """feature-extraction""": DPTModel,
             """image-segmentation""": DPTForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

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







     def  snake_case_			(							self       )			->							Union[str, Any]:
          snake_case :			List[Any]					   = DPTModelTester(self       )
          snake_case :			Optional[Any]					   = ConfigTester(self       ,config_class=__a       ,has_text_modality=__a       ,hidden_size=37       )







     def  snake_case_			(							self       )			->							Union[str, Any]:
          self.config_tester.run_common_tests()







     @unittest.skip(reason="""DPT does not use inputs_embeds"""       )
     def  snake_case_			(							self       )			->							str:
          pass







     def  snake_case_			(							self       )			->							Dict:
          snake_case   ,		snake_case :			List[Any]					   = self.model_tester.prepare_config_and_inputs_for_common()

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







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

          for model_class in self.all_model_classes:
               snake_case :			Tuple					   = model_class(__a       )
               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 :			int					   = ["""pixel_values"""]
               self.assertListEqual(arg_names[:1]       ,__a       )







     def  snake_case_			(							self       )			->							Optional[Any]:
          snake_case :			Optional[Any]					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__a       )







     def  snake_case_			(							self       )			->							Optional[Any]:
          snake_case :			Optional[Any]					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_depth_estimation(*__a       )







     def  snake_case_			(							self       )			->							Optional[Any]:
          snake_case :			List[Any]					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*__a       )







     def  snake_case_			(							self       )			->							int:
          for model_class in self.all_model_classes:
               if model_class.__name__ == "DPTForDepthEstimation":
                    continue

               snake_case   ,		snake_case :			Optional[int]					   = self.model_tester.prepare_config_and_inputs_for_common()
               snake_case :			Optional[Any]					   = True

               if model_class in get_values(__a       ):
                    continue

               snake_case :			List[str]					   = model_class(__a       )
               model.to(__a       )
               model.train()
               snake_case :			Dict					   = self._prepare_for_class(__a       ,__a       ,return_labels=__a       )
               snake_case :			int					   = model(**__a       ).loss
               loss.backward()







     def  snake_case_			(							self       )			->							Tuple:
          for model_class in self.all_model_classes:
               if model_class.__name__ == "DPTForDepthEstimation":
                    continue

               snake_case   ,		snake_case :			Tuple					   = self.model_tester.prepare_config_and_inputs_for_common()
               snake_case :			Optional[Any]					   = False
               snake_case :			Optional[int]					   = True

               if model_class in get_values(__a       ) or not model_class.supports_gradient_checkpointing:
                    continue
               snake_case :			Any					   = model_class(__a       )
               model.to(__a       )
               model.gradient_checkpointing_enable()
               model.train()
               snake_case :			Optional[Any]					   = self._prepare_for_class(__a       ,__a       ,return_labels=__a       )
               snake_case :			Union[str, Any]					   = model(**__a       ).loss
               loss.backward()







     def  snake_case_			(							self       )			->							Tuple:
          snake_case   ,		snake_case :			Any					   = self.model_tester.prepare_config_and_inputs_for_common()

          snake_case :			Tuple					   = _config_zero_init(__a       )
          for model_class in self.all_model_classes:
               snake_case :			List[Any]					   = model_class(config=__a       )
               # Skip the check for the backbone
               snake_case :			Tuple					   = []
               for name, module in model.named_modules():
                    if module.__class__.__name__ == "DPTViTHybridEmbeddings":
                         snake_case :			int					   = [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  snake_case_			(							self       )			->							str:
          pass







     @slow
     def  snake_case_			(							self       )			->							Optional[Any]:
          for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               snake_case :			Optional[int]					   = DPTModel.from_pretrained(__a       )
               self.assertIsNotNone(__a       )



def 					lowerCamelCase__							(			):
     snake_case :			str					   = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
     return image







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





     '''simple docstring'''



     def  snake_case_			(							self       )			->							List[Any]:
          snake_case :			Optional[Any]					   = DPTImageProcessor.from_pretrained("""Intel/dpt-large"""       )
          snake_case :			Any					   = DPTForDepthEstimation.from_pretrained("""Intel/dpt-large"""       ).to(__a       )

          snake_case :			Optional[Any]					   = prepare_img()
          snake_case :			Union[str, Any]					   = image_processor(images=__a       ,return_tensors="""pt"""       ).to(__a       )

          # forward pass
          with torch.no_grad():
               snake_case :			Dict					   = model(**__a       )
               snake_case :			Tuple					   = outputs.predicted_depth

          # verify the predicted depth
          snake_case :			List[str]					   = torch.Size((1, 384, 384)       )
          self.assertEqual(predicted_depth.shape       ,__a       )

          snake_case :			int					   = torch.tensor(
              [[6.3_199, 6.3_629, 6.4_148], [6.3_850, 6.3_615, 6.4_166], [6.3_519, 6.3_176, 6.3_575]]       ).to(__a       )

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







     def  snake_case_			(							self       )			->							Union[str, Any]:
          snake_case :			List[str]					   = DPTImageProcessor.from_pretrained("""Intel/dpt-large-ade"""       )
          snake_case :			Dict					   = DPTForSemanticSegmentation.from_pretrained("""Intel/dpt-large-ade"""       ).to(__a       )

          snake_case :			Optional[Any]					   = prepare_img()
          snake_case :			Dict					   = image_processor(images=__a       ,return_tensors="""pt"""       ).to(__a       )

          # forward pass
          with torch.no_grad():
               snake_case :			Optional[int]					   = model(**__a       )

          # verify the logits
          snake_case :			int					   = torch.Size((1, 150, 480, 480)       )
          self.assertEqual(outputs.logits.shape       ,__a       )

          snake_case :			Any					   = torch.tensor(
              [[4.0_480, 4.2_420, 4.4_360], [4.3_124, 4.5_693, 4.8_261], [4.5_768, 4.8_965, 5.2_163]]       ).to(__a       )

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







     def  snake_case_			(							self       )			->							Optional[Any]:
          snake_case :			Optional[Any]					   = DPTImageProcessor.from_pretrained("""Intel/dpt-large-ade"""       )
          snake_case :			Optional[int]					   = DPTForSemanticSegmentation.from_pretrained("""Intel/dpt-large-ade"""       ).to(__a       )

          snake_case :			str					   = prepare_img()
          snake_case :			Any					   = image_processor(images=__a       ,return_tensors="""pt"""       ).to(__a       )

          # forward pass
          with torch.no_grad():
               snake_case :			Dict					   = model(**__a       )

          snake_case :			Optional[Any]					   = outputs.logits.detach().cpu()

          snake_case :			int					   = image_processor.post_process_semantic_segmentation(outputs=__a       ,target_sizes=[(500, 300)]       )
          snake_case :			List[Any]					   = torch.Size((500, 300)       )
          self.assertEqual(segmentation[0].shape       ,__a       )

          snake_case :			Any					   = image_processor.post_process_semantic_segmentation(outputs=__a       )
          snake_case :			List[Any]					   = torch.Size((480, 480)       )
          self.assertEqual(segmentation[0].shape       ,__a       )









'''simple docstring'''







def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 9 / 5) + 32    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) + 273.15    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 9 / 5) + 491.67    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) - 32) * 5 / 9    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(((float(__lowercase							) - 32) * 5 / 9) + 273.15    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) + 459.67    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) - 273.15    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(((float(__lowercase							) - 273.15) * 9 / 5) + 32    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 9 / 5)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) - 491.67) * 5 / 9    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) - 459.67    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 5 / 9)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 1.25 + 273.15)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 2.25 + 32)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 1.25)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 2.25 + 32 + 459.67)    ,      __lowercase							)


if __name__ == "__main__":
      import doctest

      doctest.testmod()



