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



      """simple docstring"""







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




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

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

          __lowercase						:     List[str]		      =    self.get_config()

          return config, pixel_values, labels




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




      def 						snake_case_     ( self						:    Optional[int]			,    _snake_case						:    List[str]			,    _snake_case						:    Optional[int]			,    _snake_case						:    Dict			):
          __lowercase						:     Union[str, Any]		      =    DPTModel(config=_snake_case			)
          model.to(_snake_case			)
          model.eval()
          __lowercase						:     Optional[int]		      =    model(_snake_case			)
          self.parent.assertEqual(result.last_hidden_state.shape			,    (self.batch_size, self.seq_length, self.hidden_size)			)




      def 						snake_case_     ( self						:    int			,    _snake_case						:    Optional[Any]			,    _snake_case						:    Union[str, Any]			,    _snake_case						:    Tuple			):
          __lowercase						:     List[str]		      =    self.num_labels
          __lowercase						:     Union[str, Any]		      =    DPTForDepthEstimation(_snake_case			)
          model.to(_snake_case			)
          model.eval()
          __lowercase						:     int		      =    model(_snake_case			)
          self.parent.assertEqual(result.predicted_depth.shape			,    (self.batch_size, self.image_size, self.image_size)			)




      def 						snake_case_     ( self						:    Optional[Any]			,    _snake_case						:    str			,    _snake_case						:    int			,    _snake_case						:    str			):
          __lowercase						:     Dict		      =    self.num_labels
          __lowercase						:     Any		      =    DPTForSemanticSegmentation(_snake_case			)
          model.to(_snake_case			)
          model.eval()
          __lowercase						:     Union[str, Any]		      =    model(_snake_case			,    labels=_snake_case			)
          self.parent.assertEqual(
              result.logits.shape			,    (self.batch_size, self.num_labels, self.image_size, self.image_size)			)




      def 						snake_case_     ( self						:    Optional[int]			):
          __lowercase						:     List[str]		      =    self.prepare_config_and_inputs()
          __lowercase      , __lowercase      , __lowercase						:     int		      =    config_and_inputs
          __lowercase						:     Tuple		      =    {'''pixel_values''': pixel_values}
          return config, inputs_dict






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



      """simple docstring"""







      A__		:     int       				=      (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
      A__		:     Optional[Any]       				=      (
          {
              '''depth-estimation''': DPTForDepthEstimation,
              '''feature-extraction''': DPTModel,
              '''image-segmentation''': DPTForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      A__		:     Optional[int]       				=      False
      A__		:     str       				=      False
      A__		:     Optional[int]       				=      False




      def 						snake_case_     ( self						:    Any			):
          __lowercase						:     Union[str, Any]		      =    DPTModelTester(self			)
          __lowercase						:     int		      =    ConfigTester(self			,    config_class=_snake_case			,    has_text_modality=_snake_case			,    hidden_size=37			)




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




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




      def 						snake_case_     ( self						:    Tuple			):
          __lowercase      , __lowercase						:     Tuple		      =    self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              __lowercase						:     Dict		      =    model_class(_snake_case			)
              self.assertIsInstance(model.get_input_embeddings()			,    (nn.Module)			)
              __lowercase						:     int		      =    model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(_snake_case			,    nn.Linear			)			)




      def 						snake_case_     ( self						:    str			):
          __lowercase      , __lowercase						:     str		      =    self.model_tester.prepare_config_and_inputs_for_common()

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

              __lowercase						:     Dict		      =    ['''pixel_values''']
              self.assertListEqual(arg_names[:1]			,    _snake_case			)




      def 						snake_case_     ( self						:    List[str]			):
          __lowercase						:     str		      =    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_snake_case			)




      def 						snake_case_     ( self						:    Dict			):
          __lowercase						:     Optional[Any]		      =    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_depth_estimation(*_snake_case			)




      def 						snake_case_     ( self						:    List[Any]			):
          __lowercase						:     Tuple		      =    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*_snake_case			)




      def 						snake_case_     ( self						:    List[str]			):
          for model_class in self.all_model_classes:
              if model_class.__name__ == "DPTForDepthEstimation":
                  continue

              __lowercase      , __lowercase						:     List[Any]		      =    self.model_tester.prepare_config_and_inputs_for_common()
              __lowercase						:     Any		      =    True

              if model_class in get_values(_snake_case			):
                  continue

              __lowercase						:     Dict		      =    model_class(_snake_case			)
              model.to(_snake_case			)
              model.train()
              __lowercase						:     List[Any]		      =    self._prepare_for_class(_snake_case			,    _snake_case			,    return_labels=_snake_case			)
              __lowercase						:     int		      =    model(**_snake_case			).loss
              loss.backward()




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

              __lowercase      , __lowercase						:     Tuple		      =    self.model_tester.prepare_config_and_inputs_for_common()
              __lowercase						:     str		      =    False
              __lowercase						:     Union[str, Any]		      =    True

              if model_class in get_values(_snake_case			) or not model_class.supports_gradient_checkpointing:
                  continue
              __lowercase						:     Any		      =    model_class(_snake_case			)
              model.to(_snake_case			)
              model.gradient_checkpointing_enable()
              model.train()
              __lowercase						:     List[Any]		      =    self._prepare_for_class(_snake_case			,    _snake_case			,    return_labels=_snake_case			)
              __lowercase						:     Any		      =    model(**_snake_case			).loss
              loss.backward()




      def 						snake_case_     ( self						:    Dict			):
          __lowercase      , __lowercase						:     str		      =    self.model_tester.prepare_config_and_inputs_for_common()

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




      @slow
      def 						snake_case_     ( self						:    List[str]			):
          for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __lowercase						:     Tuple		      =    DPTModel.from_pretrained(_snake_case			)
              self.assertIsNotNone(_snake_case			)






def       UpperCAmelCase_					(  )	->  Optional[int]:
    __lowercase						:     Any		      =    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
    return image





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



      """simple docstring"""







      def 						snake_case_     ( self						:    str			):
          __lowercase						:     Tuple		      =    DPTImageProcessor.from_pretrained('''Intel/dpt-large'''			)
          __lowercase						:     Optional[int]		      =    DPTForDepthEstimation.from_pretrained('''Intel/dpt-large'''			).to(_snake_case			)

          __lowercase						:     int		      =    prepare_img()
          __lowercase						:     Union[str, Any]		      =    image_processor(images=_snake_case			,    return_tensors='''pt'''			).to(_snake_case			)

          # forward pass
          with torch.no_grad():
              __lowercase						:     Dict		      =    model(**_snake_case			)
              __lowercase						:     str		      =    outputs.predicted_depth

          # verify the predicted depth
          __lowercase						:     Optional[Any]		      =    torch.Size((1, 384, 384)			)
          self.assertEqual(predicted_depth.shape			,    _snake_case			)

          __lowercase						:     int		      =    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(_snake_case			)

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




      def 						snake_case_     ( self						:    List[Any]			):
          __lowercase						:     Dict		      =    DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''			)
          __lowercase						:     Tuple		      =    DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''			).to(_snake_case			)

          __lowercase						:     Union[str, Any]		      =    prepare_img()
          __lowercase						:     Any		      =    image_processor(images=_snake_case			,    return_tensors='''pt'''			).to(_snake_case			)

          # forward pass
          with torch.no_grad():
              __lowercase						:     Any		      =    model(**_snake_case			)

          # verify the logits
          __lowercase						:     List[str]		      =    torch.Size((1, 150, 480, 480)			)
          self.assertEqual(outputs.logits.shape			,    _snake_case			)

          __lowercase						:     List[str]		      =    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(_snake_case			)

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




      def 						snake_case_     ( self						:    List[Any]			):
          __lowercase						:     Dict		      =    DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''			)
          __lowercase						:     Optional[int]		      =    DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''			).to(_snake_case			)

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

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

          __lowercase						:     int		      =    outputs.logits.detach().cpu()

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

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




import importlib.metadata
import sys

from transformers.testing_utils import TestCasePlus
from transformers.utils.versions import require_version, require_version_core


__lowerCAmelCase   :     Optional[Any]      =						importlib.metadata.version("numpy")
__lowerCAmelCase   :     Any      =						".".join([str(x) for x in sys.version_info[:3]])


class   __lowerCAmelCase		(		lowerCAmelCase_ ):



      """simple docstring"""







      def 						snake_case_     ( self						:    List[Any]			):
          # lt + different version strings
          require_version_core('''numpy<1000.4.5'''			)
          require_version_core('''numpy<1000.4'''			)
          require_version_core('''numpy<1000'''			)

          # le
          require_version_core('''numpy<=1000.4.5'''			)
          require_version_core(F'numpy<={numpy_ver}'			)

          # eq
          require_version_core(F'numpy=={numpy_ver}'			)

          # ne
          require_version_core('''numpy!=1000.4.5'''			)

          # ge
          require_version_core('''numpy>=1.0'''			)
          require_version_core('''numpy>=1.0.0'''			)
          require_version_core(F'numpy>={numpy_ver}'			)

          # gt
          require_version_core('''numpy>1.0.0'''			)

          # mix
          require_version_core('''numpy>1.0.0,<1000'''			)

          # requirement w/o version
          require_version_core('''numpy'''			)

          # unmet requirements due to version conflict
          for req in ["numpy==1.0.0", "numpy>=1000.0.0", F'numpy<{numpy_ver}']:
              try:
                  require_version_core(_snake_case			)
              except ImportError as e:
                  self.assertIn(F'{req} is required'			,    str(_snake_case			)			)
                  self.assertIn('''but found'''			,    str(_snake_case			)			)

        # unmet requirements due to missing module
          for req in ["numpipypie>1", "numpipypie2"]:
              try:
                  require_version_core(_snake_case			)
              except importlib.metadata.PackageNotFoundError as e:
                  self.assertIn(F'The \'{req}\' distribution was not found and is required by this application'			,    str(_snake_case			)			)
                  self.assertIn('''Try: pip install transformers -U'''			,    str(_snake_case			)			)

        # bogus requirements formats:
        # 1. whole thing
          for req in ["numpy??1.0.0", "numpy1.0.0"]:
              try:
                  require_version_core(_snake_case			)
              except ValueError as e:
                  self.assertIn('''requirement needs to be in the pip package format'''			,    str(_snake_case			)			)
        # 2. only operators
          for req in ["numpy=1.0.0", "numpy == 1.00", "numpy<>1.0.0", "numpy><1.00", "numpy>>1.0.0"]:
              try:
                  require_version_core(_snake_case			)
              except ValueError as e:
                  self.assertIn('''need one of '''			,    str(_snake_case			)			)




      def 						snake_case_     ( self						:    List[str]			):
          # matching requirement
          require_version('''python>=3.6.0'''			)

          # not matching requirements
          for req in ["python>9.9.9", "python<3.0.0"]:
              try:
                  require_version_core(_snake_case			)
              except ImportError as e:
                  self.assertIn(F'{req} is required'			,    str(_snake_case			)			)
                  self.assertIn(F'but found python=={python_ver}'			,    str(_snake_case			)			)


