





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		:					Union[str, Any]		,lowerCamelCase__		:					Optional[int]		,lowerCamelCase__		:					Optional[int]=2		,lowerCamelCase__		:					int=32		,lowerCamelCase__		:					Tuple=16		,lowerCamelCase__		:					Dict=3		,lowerCamelCase__		:					Dict=True		,lowerCamelCase__		:					Optional[Any]=True		,lowerCamelCase__		:					Optional[Any]=32		,lowerCamelCase__		:					Any=4		,lowerCamelCase__		:					Optional[int]=[0, 1, 2, 3]		,lowerCamelCase__		:					str=4		,lowerCamelCase__		:					Optional[Any]=37		,lowerCamelCase__		:					str="gelu"		,lowerCamelCase__		:					Optional[int]=0.1		,lowerCamelCase__		:					Any=0.1		,lowerCamelCase__		:					Any=0.02		,lowerCamelCase__		:					Optional[int]=3		,lowerCamelCase__		:					int=[1, 384, 24, 24]		,lowerCamelCase__		:					Union[str, Any]=True		,lowerCamelCase__		:					Any=None		,)  ->	Optional[Any]:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		parent
											SCREAMING_SNAKE_CASE	=		batch_size
											SCREAMING_SNAKE_CASE	=		image_size
											SCREAMING_SNAKE_CASE	=		patch_size
											SCREAMING_SNAKE_CASE	=		num_channels
											SCREAMING_SNAKE_CASE	=		is_training
											SCREAMING_SNAKE_CASE	=		use_labels
											SCREAMING_SNAKE_CASE	=		hidden_size
											SCREAMING_SNAKE_CASE	=		num_hidden_layers
											SCREAMING_SNAKE_CASE	=		backbone_out_indices
											SCREAMING_SNAKE_CASE	=		num_attention_heads
											SCREAMING_SNAKE_CASE	=		intermediate_size
											SCREAMING_SNAKE_CASE	=		hidden_act
											SCREAMING_SNAKE_CASE	=		hidden_dropout_prob
											SCREAMING_SNAKE_CASE	=		attention_probs_dropout_prob
											SCREAMING_SNAKE_CASE	=		initializer_range
											SCREAMING_SNAKE_CASE	=		num_labels
											SCREAMING_SNAKE_CASE	=		backbone_featmap_shape
											SCREAMING_SNAKE_CASE	=		scope
											SCREAMING_SNAKE_CASE	=		is_hybrid
											# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
											SCREAMING_SNAKE_CASE	=		(image_size // patch_size) ** 2
											SCREAMING_SNAKE_CASE	=		num_patches + 1






					def        SCREAMING_SNAKE_CASE__						(							self		:					str )  ->	int:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

											SCREAMING_SNAKE_CASE	=		self.get_config()

											return config, pixel_values, labels






					def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	List[Any]:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		{
											    """global_padding""": """same""",
											    """layer_type""": """bottleneck""",
											    """depths""": [3, 4, 9],
											    """out_features""": ["""stage1""", """stage2""", """stage3"""],
											    """embedding_dynamic_padding""": True,
											    """hidden_sizes""": [96, 192, 384, 768],
											    """num_groups""": 2,
											}

											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=__UpperCamelCase		,initializer_range=self.initializer_range		,is_hybrid=self.is_hybrid		,backbone_config=__UpperCamelCase		,backbone_featmap_shape=self.backbone_featmap_shape		,)






					def        SCREAMING_SNAKE_CASE__						(							self		:					Any		,lowerCamelCase__		:					Dict		,lowerCamelCase__		:					Union[str, Any]		,lowerCamelCase__		:					Optional[Any] )  ->	Dict:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		DPTModel(config=__UpperCamelCase )
											model.to(__UpperCamelCase )
											model.eval()
											SCREAMING_SNAKE_CASE	=		model(__UpperCamelCase )
											self.parent.assertEqual(result.last_hidden_state.shape		,(self.batch_size, self.seq_length, self.hidden_size) )






					def        SCREAMING_SNAKE_CASE__						(							self		:					List[Any]		,lowerCamelCase__		:					Optional[int]		,lowerCamelCase__		:					str		,lowerCamelCase__		:					List[Any] )  ->	int:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		self.num_labels
											SCREAMING_SNAKE_CASE	=		DPTForDepthEstimation(__UpperCamelCase )
											model.to(__UpperCamelCase )
											model.eval()
											SCREAMING_SNAKE_CASE	=		model(__UpperCamelCase )
											self.parent.assertEqual(result.predicted_depth.shape		,(self.batch_size, self.image_size, self.image_size) )






					def        SCREAMING_SNAKE_CASE__						(							self		:					Any		,lowerCamelCase__		:					List[Any]		,lowerCamelCase__		:					Optional[Any]		,lowerCamelCase__		:					Union[str, Any] )  ->	List[Any]:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		self.num_labels
											SCREAMING_SNAKE_CASE	=		DPTForSemanticSegmentation(__UpperCamelCase )
											model.to(__UpperCamelCase )
											model.eval()
											SCREAMING_SNAKE_CASE	=		model(__UpperCamelCase		,labels=__UpperCamelCase )
											self.parent.assertEqual(
											    result.logits.shape		,(self.batch_size, self.num_labels, self.image_size, self.image_size) )






					def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	Any:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		self.prepare_config_and_inputs()
											SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		config_and_inputs
											SCREAMING_SNAKE_CASE	=		{"""pixel_values""": pixel_values}
											return config, inputs_dict

@require_torch
class 	UpperCamelCase__				(   _UpperCAmelCase							,   _UpperCAmelCase							,   unittest.TestCase     ):



					'''simple docstring'''

					__snake_case					:			Dict				=    (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
					__snake_case					:			int				=    (
					    {
					        'depth-estimation': DPTForDepthEstimation,
					        'feature-extraction': DPTModel,
					        'image-segmentation': DPTForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					__snake_case					:			str				=    False
					__snake_case					:			List[str]				=    False
					__snake_case					:			Dict				=    False






					def        SCREAMING_SNAKE_CASE__						(							self		:					Any )  ->	Any:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		DPTModelTester(self )
											SCREAMING_SNAKE_CASE	=		ConfigTester(self		,config_class=__UpperCamelCase		,has_text_modality=__UpperCamelCase		,hidden_size=37 )






					def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int] )  ->	Any:




											'''simple docstring'''


											self.config_tester.run_common_tests()






					@unittest.skip(reason="""DPT does not use inputs_embeds""" )
					def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	Tuple:




											'''simple docstring'''


											pass






					def        SCREAMING_SNAKE_CASE__						(							self		:					int )  ->	Any:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs_for_common()

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






					def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int] )  ->	Optional[Any]:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs_for_common()

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

																	SCREAMING_SNAKE_CASE	=		["""pixel_values"""]
																	self.assertListEqual(arg_names[:1]		,__UpperCamelCase )






					def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any] )  ->	Dict:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__UpperCamelCase )






					def        SCREAMING_SNAKE_CASE__						(							self		:					str )  ->	int:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_depth_estimation(*__UpperCamelCase )






					def        SCREAMING_SNAKE_CASE__						(							self		:					Any )  ->	Tuple:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCamelCase )






					def        SCREAMING_SNAKE_CASE__						(							self		:					str )  ->	Any:




											'''simple docstring'''


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

																	SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs_for_common()
																	SCREAMING_SNAKE_CASE	=		True

																	if model_class in get_values(__UpperCamelCase ):
																							continue

																	SCREAMING_SNAKE_CASE	=		model_class(__UpperCamelCase )
																	model.to(__UpperCamelCase )
																	model.train()
																	SCREAMING_SNAKE_CASE	=		self._prepare_for_class(__UpperCamelCase		,__UpperCamelCase		,return_labels=__UpperCamelCase )
																	SCREAMING_SNAKE_CASE	=		model(**__UpperCamelCase ).loss
																	loss.backward()






					def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Dict:




											'''simple docstring'''


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

																	SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs_for_common()
																	SCREAMING_SNAKE_CASE	=		False
																	SCREAMING_SNAKE_CASE	=		True

																	if model_class in get_values(__UpperCamelCase ) or not model_class.supports_gradient_checkpointing:
																							continue
																	SCREAMING_SNAKE_CASE	=		model_class(__UpperCamelCase )
																	model.to(__UpperCamelCase )
																	model.gradient_checkpointing_enable()
																	model.train()
																	SCREAMING_SNAKE_CASE	=		self._prepare_for_class(__UpperCamelCase		,__UpperCamelCase		,return_labels=__UpperCamelCase )
																	SCREAMING_SNAKE_CASE	=		model(**__UpperCamelCase ).loss
																	loss.backward()






					def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple )  ->	List[str]:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs_for_common()

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




											'''simple docstring'''


											pass






					@slow
					def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int] )  ->	List[Any]:




											'''simple docstring'''


											for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
																	SCREAMING_SNAKE_CASE	=		DPTModel.from_pretrained(__UpperCamelCase )
																	self.assertIsNotNone(__UpperCamelCase )






					def        SCREAMING_SNAKE_CASE__						(							self		:					List[Any] )  ->	Optional[int]:




											'''simple docstring'''


											SCREAMING_SNAKE_CASE,      SCREAMING_SNAKE_CASE	=		self.model_tester.prepare_config_and_inputs_for_common()
											SCREAMING_SNAKE_CASE	=		"""add"""
											with self.assertRaises(__UpperCamelCase ):
																	SCREAMING_SNAKE_CASE	=		DPTForDepthEstimation(__UpperCamelCase )



def      __lowercase     (   )				->     int:


						'''simple docstring'''


						SCREAMING_SNAKE_CASE	=		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
						return image



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



					'''simple docstring'''

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




											'''simple docstring'''


											SCREAMING_SNAKE_CASE	=		DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas""" )
											SCREAMING_SNAKE_CASE	=		DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas""" ).to(__UpperCamelCase )

											SCREAMING_SNAKE_CASE	=		prepare_img()
											SCREAMING_SNAKE_CASE	=		image_processor(images=__UpperCamelCase		,return_tensors="""pt""" ).to(__UpperCamelCase )

											# forward pass
											with torch.no_grad():
																	SCREAMING_SNAKE_CASE	=		model(**__UpperCamelCase )
																	SCREAMING_SNAKE_CASE	=		outputs.predicted_depth

											# verify the predicted depth
											SCREAMING_SNAKE_CASE	=		torch.Size((1, 384, 384) )
											self.assertEqual(predicted_depth.shape		,__UpperCamelCase )

											SCREAMING_SNAKE_CASE	=		torch.tensor(
											    [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]] ).to(__UpperCamelCase )

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









import pytest

from datasets import inspect_metric, list_metrics, load_metric



@pytest.fixture
def      __lowercase     (   _SCREAMING_SNAKE_CASE			)				->     List[Any]:


      '''simple docstring'''


      monkeypatch.setattr("""datasets.utils.deprecation_utils._emitted_deprecation_warnings"""				,		set()			)



@pytest.fixture
def      __lowercase     (   _SCREAMING_SNAKE_CASE			)				->     Dict:


      '''simple docstring'''


      class 	UpperCamelCase__				:



           '''simple docstring'''

           def __init__(							self		:					int		,lowerCamelCase__		:					Dict )  ->	List[Any]:




                 '''simple docstring'''


                 SCREAMING_SNAKE_CASE	=		metric_id

      class 	UpperCamelCase__				:



           '''simple docstring'''

           __snake_case					:			List[str]				=    [MetricMock(lowerCAmelCase_     ) for metric_id in ["accuracy", "mse", "precision", "codeparrot/apps_metric"]]






           def        SCREAMING_SNAKE_CASE__						(							self		:					Optional[int] )  ->	str:




                 '''simple docstring'''


                 return self._metrics
      monkeypatch.setattr("""datasets.inspect.huggingface_hub"""				,		HfhMock()			)



@pytest.mark.parametrize(
    """func, args"""				,		[(load_metric, ("""metrics/mse""",)), (list_metrics, ()), (inspect_metric, ("""metrics/mse""", """tmp_path"""))]			)
def      __lowercase     (   _SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE				,		_SCREAMING_SNAKE_CASE			)				->     Union[str, Any]:


      '''simple docstring'''


      if "tmp_path" in args:
            SCREAMING_SNAKE_CASE	=		tuple(arg if arg != """tmp_path""" else tmp_path for arg in args			)
      with pytest.warns(_SCREAMING_SNAKE_CASE				,		match="""https://huggingface.co/docs/evaluate"""			):
            func(*_SCREAMING_SNAKE_CASE			)


