






"""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,	lowerCamelCase_,	lowerCamelCase_=2,	lowerCamelCase_=3_2,	lowerCamelCase_=1_6,	lowerCamelCase_=3,	lowerCamelCase_=True,	lowerCamelCase_=True,	lowerCamelCase_=3_2,	lowerCamelCase_=4,	lowerCamelCase_=[0, 1, 2, 3],	lowerCamelCase_=4,	lowerCamelCase_=3_7,	lowerCamelCase_="gelu",	lowerCamelCase_=0.1,	lowerCamelCase_=0.1,	lowerCamelCase_=0.02,	lowerCamelCase_=3,	lowerCamelCase_=False,	lowerCamelCase_=None,	):

       '''simple docstring'''



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




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Union[str, Any]								=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

       lowerCamelCase__	:     Optional[int]								=		None
       if self.use_labels:
        lowerCamelCase__	:     str								=		ids_tensor([self.batch_size, self.image_size, self.image_size],	self.num_labels   )

       lowerCamelCase__	:     str								=		self.get_config()

       return config, pixel_values, labels




      def      a__				(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=lowerCamelCase_,	initializer_range=self.initializer_range,	is_hybrid=self.is_hybrid,	)




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       lowerCamelCase__	:     Any								=		DPTModel(config=lowerCamelCase_   )
       model.to(lowerCamelCase_   )
       model.eval()
       lowerCamelCase__	:     Tuple								=		model(lowerCamelCase_   )
       self.parent.assertEqual(result.last_hidden_state.shape,	(self.batch_size, self.seq_length, self.hidden_size)   )




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       lowerCamelCase__	:     Tuple								=		self.num_labels
       lowerCamelCase__	:     Union[str, Any]								=		DPTForDepthEstimation(lowerCamelCase_   )
       model.to(lowerCamelCase_   )
       model.eval()
       lowerCamelCase__	:     Union[str, Any]								=		model(lowerCamelCase_   )
       self.parent.assertEqual(result.predicted_depth.shape,	(self.batch_size, self.image_size, self.image_size)   )




      def      a__				(self,	lowerCamelCase_,	lowerCamelCase_,	lowerCamelCase_   ):

       '''simple docstring'''



       lowerCamelCase__	:     Tuple								=		self.num_labels
       lowerCamelCase__	:     int								=		DPTForSemanticSegmentation(lowerCamelCase_   )
       model.to(lowerCamelCase_   )
       model.eval()
       lowerCamelCase__	:     Optional[int]								=		model(lowerCamelCase_,	labels=lowerCamelCase_   )
       self.parent.assertEqual(
           result.logits.shape,	(self.batch_size, self.num_labels, self.image_size, self.image_size)   )





      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[int]								=		self.prepare_config_and_inputs()
       lowerCamelCase__							,	lowerCamelCase__							,	lowerCamelCase__	:     Union[str, Any]								=		config_and_inputs
       lowerCamelCase__	:     Union[str, Any]								=		{'pixel_values': pixel_values}
       return config, inputs_dict



@require_torch
class 						a_ (      snake_case_    ,		snake_case_    ,		unittest.TestCase					):







      '''simple docstring'''

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

      lowerCamelCase__			:							Dict					=      False
      lowerCamelCase__			:							Optional[int]					=      False
      lowerCamelCase__			:							Dict					=      False




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Dict								=		DPTModelTester(self   )
       lowerCamelCase__	:     List[Any]								=		ConfigTester(self,	config_class=lowerCamelCase_,	has_text_modality=lowerCamelCase_,	hidden_size=3_7   )




      def      a__				(self   ):

       '''simple docstring'''



       self.config_tester.run_common_tests()




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

       '''simple docstring'''



       pass




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__							,	lowerCamelCase__	:     Tuple								=		self.model_tester.prepare_config_and_inputs_for_common()

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




      def      a__				(self   ):

       '''simple docstring'''



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

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

        lowerCamelCase__	:     Tuple								=		['pixel_values']
        self.assertListEqual(arg_names[:1],	lowerCamelCase_   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Optional[int]								=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase_   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     Union[str, Any]								=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_depth_estimation(*lowerCamelCase_   )




      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     int								=		self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase_   )




      def      a__				(self   ):

       '''simple docstring'''



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

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

        if model_class in get_values(lowerCamelCase_   ):
         continue

        lowerCamelCase__	:     str								=		model_class(lowerCamelCase_   )
        model.to(lowerCamelCase_   )
        model.train()
        lowerCamelCase__	:     int								=		self._prepare_for_class(lowerCamelCase_,	lowerCamelCase_,	return_labels=lowerCamelCase_   )
        lowerCamelCase__	:     Tuple								=		model(**lowerCamelCase_   ).loss
        loss.backward()




      def      a__				(self   ):

       '''simple docstring'''



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

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

        if model_class in get_values(lowerCamelCase_   ) or not model_class.supports_gradient_checkpointing:
         continue
        lowerCamelCase__	:     Tuple								=		model_class(lowerCamelCase_   )
        model.to(lowerCamelCase_   )
        model.gradient_checkpointing_enable()
        model.train()
        lowerCamelCase__	:     Optional[int]								=		self._prepare_for_class(lowerCamelCase_,	lowerCamelCase_,	return_labels=lowerCamelCase_   )
        lowerCamelCase__	:     str								=		model(**lowerCamelCase_   ).loss
        loss.backward()




      def      a__				(self   ):

       '''simple docstring'''



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

       lowerCamelCase__	:     Tuple								=		_config_zero_init(lowerCamelCase_   )
       for model_class in self.all_model_classes:
        lowerCamelCase__	:     List[str]								=		model_class(config=lowerCamelCase_   )
        # Skip the check for the backbone
        lowerCamelCase__	:     Dict								=		[]
        for name, module in model.named_modules():
         if module.__class__.__name__ == "DPTViTHybridEmbeddings":
          lowerCamelCase__	:     Optional[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      a__				(self   ):

       '''simple docstring'''



       pass





      @slow
      def      a__				(self   ):

       '''simple docstring'''



       for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCamelCase__	:     Optional[int]								=		DPTModel.from_pretrained(lowerCamelCase_   )
        self.assertIsNotNone(lowerCamelCase_   )






def 			lowerCamelCase_    (		):
 lowerCamelCase__	:     int								=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'							)
 return image





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







      '''simple docstring'''

      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[str]								=		DPTImageProcessor.from_pretrained('Intel/dpt-large'   )
       lowerCamelCase__	:     Tuple								=		DPTForDepthEstimation.from_pretrained('Intel/dpt-large'   ).to(lowerCamelCase_   )

       lowerCamelCase__	:     List[Any]								=		prepare_img()
       lowerCamelCase__	:     List[Any]								=		image_processor(images=lowerCamelCase_,	return_tensors='pt'   ).to(lowerCamelCase_   )

       # forward pass
       with torch.no_grad():
        lowerCamelCase__	:     List[Any]								=		model(**lowerCamelCase_   )
        lowerCamelCase__	:     Tuple								=		outputs.predicted_depth

       # verify the predicted depth
       lowerCamelCase__	:     Union[str, Any]								=		torch.Size((1, 3_8_4, 3_8_4)   )
       self.assertEqual(predicted_depth.shape,	lowerCamelCase_   )

       lowerCamelCase__	:     Dict								=		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(lowerCamelCase_   )

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




      def      a__				(self   ):

       '''simple docstring'''



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

       lowerCamelCase__	:     str								=		prepare_img()
       lowerCamelCase__	:     Optional[int]								=		image_processor(images=lowerCamelCase_,	return_tensors='pt'   ).to(lowerCamelCase_   )

       # forward pass
       with torch.no_grad():
        lowerCamelCase__	:     Dict								=		model(**lowerCamelCase_   )

       # verify the logits
       lowerCamelCase__	:     Optional[int]								=		torch.Size((1, 1_5_0, 4_8_0, 4_8_0)   )
       self.assertEqual(outputs.logits.shape,	lowerCamelCase_   )

       lowerCamelCase__	:     int								=		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(lowerCamelCase_   )

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





      def      a__				(self   ):

       '''simple docstring'''



       lowerCamelCase__	:     List[str]								=		DPTImageProcessor.from_pretrained('Intel/dpt-large-ade'   )
       lowerCamelCase__	:     Optional[int]								=		DPTForSemanticSegmentation.from_pretrained('Intel/dpt-large-ade'   ).to(lowerCamelCase_   )

       lowerCamelCase__	:     Union[str, Any]								=		prepare_img()
       lowerCamelCase__	:     Dict								=		image_processor(images=lowerCamelCase_,	return_tensors='pt'   ).to(lowerCamelCase_   )

       # forward pass
       with torch.no_grad():
        lowerCamelCase__	:     int								=		model(**lowerCamelCase_   )

       lowerCamelCase__	:     Union[str, Any]								=		outputs.logits.detach().cpu()

       lowerCamelCase__	:     Optional[int]								=		image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase_,	target_sizes=[(5_0_0, 3_0_0)]   )
       lowerCamelCase__	:     Optional[Any]								=		torch.Size((5_0_0, 3_0_0)   )
       self.assertEqual(segmentation[0].shape,	lowerCamelCase_   )

       lowerCamelCase__	:     Dict								=		image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase_   )
       lowerCamelCase__	:     Union[str, Any]								=		torch.Size((4_8_0, 4_8_0)   )
       self.assertEqual(segmentation[0].shape,	lowerCamelCase_   )









"""simple docstring"""
from __future__ import annotations






def 			lowerCamelCase_    (		_lowerCamelCase							):
 lowerCamelCase__	:     int
 lowerCamelCase__	:     list[str]								=		list(_lowerCamelCase							)
 lowerCamelCase__							,	lowerCamelCase__	:     Union[str, Any]								=		_vector[:-1], int(_vector[-1]							)
 lowerCamelCase__	:     list[int]								=		[int(_lowerCamelCase							) for digit in __vector]

 vector.reverse()
 for i, digit in enumerate(_lowerCamelCase							):
  if i & 1 == 0:
   lowerCamelCase__	:     int								=		digit * 2
   if doubled > 9:
    doubled -= 9
   check_digit += doubled
  else:
   check_digit += digit

 return check_digit % 10 == 0


if __name__ == "__main__":
      import doctest

      doctest.testmod()
      assert is_luhn("79927398713")
      assert not is_luhn("79927398714")

