



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

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

						def       __a			(       self      :Optional[int])						->   str:
												UpperCAmelCase_					=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

												UpperCAmelCase_					=	self.get_config()

												return config, pixel_values, labels

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

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

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

						def       __a			(       self      :str  ,		_lowercase      :Tuple  ,		_lowercase      :List[str]  ,		_lowercase      :List[str])						->   Any:
												UpperCAmelCase_					=	self.num_labels
												UpperCAmelCase_					=	DPTForSemanticSegmentation(_lowercase)
												model.to(_lowercase)
												model.eval()
												UpperCAmelCase_					=	model(_lowercase  ,		labels=_lowercase)
												self.parent.assertEqual(
												    result.logits.shape  ,		(self.batch_size, self.num_labels, self.image_size, self.image_size))




						def       __a			(       self      :int)						->   Tuple:
												UpperCAmelCase_					=	self.prepare_config_and_inputs()
												UpperCAmelCase_				, UpperCAmelCase_				, UpperCAmelCase_					=	config_and_inputs
												UpperCAmelCase_					=	{'''pixel_values''': pixel_values}
												return config, inputs_dict







@require_torch
class 				a_    (						_snake_case   ,					_snake_case   ,					unittest.TestCase							):
						UpperCamelCase__ :		Dict										=(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
						UpperCamelCase__ :		Any										=(
						    {
						        "depth-estimation": DPTForDepthEstimation,
						        "feature-extraction": DPTModel,
						        "image-segmentation": DPTForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						UpperCamelCase__ :		Optional[int]										=False
						UpperCamelCase__ :		List[Any]										=False
						UpperCamelCase__ :		Dict										=False

						def       __a			(       self      :Optional[int])						->   Dict:
												UpperCAmelCase_					=	DPTModelTester(self)
												UpperCAmelCase_					=	ConfigTester(self  ,		config_class=_lowercase  ,		has_text_modality=_lowercase  ,		hidden_size=37)

						def       __a			(       self      :List[Any])						->   int:
												self.config_tester.run_common_tests()

						@unittest.skip(reason='''DPT does not use inputs_embeds''')
						def       __a			(       self      :Tuple)						->   int:
												pass

						def       __a			(       self      :int)						->   int:
												UpperCAmelCase_				, UpperCAmelCase_					=	self.model_tester.prepare_config_and_inputs_for_common()

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

						def       __a			(       self      :List[str])						->   List[Any]:
												UpperCAmelCase_				, UpperCAmelCase_					=	self.model_tester.prepare_config_and_inputs_for_common()

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

																		UpperCAmelCase_					=	['''pixel_values''']
																		self.assertListEqual(arg_names[:1]  ,		_lowercase)

						def       __a			(       self      :Dict)						->   List[str]:
												UpperCAmelCase_					=	self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_lowercase)

						def       __a			(       self      :str)						->   List[str]:
												UpperCAmelCase_					=	self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_depth_estimation(*_lowercase)

						def       __a			(       self      :Optional[Any])						->   Any:
												UpperCAmelCase_					=	self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_semantic_segmentation(*_lowercase)

						def       __a			(       self      :Any)						->   str:
												for model_class in self.all_model_classes:
																		if model_class.__name__ == "DPTForDepthEstimation":
																								continue

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

																		if model_class in get_values(_lowercase):
																								continue

																		UpperCAmelCase_					=	model_class(_lowercase)
																		model.to(_lowercase)
																		model.train()
																		UpperCAmelCase_					=	self._prepare_for_class(_lowercase  ,		_lowercase  ,		return_labels=_lowercase)
																		UpperCAmelCase_					=	model(**_lowercase).loss
																		loss.backward()

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

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

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

						def       __a			(       self      :List[str])						->   Union[str, Any]:
												UpperCAmelCase_				, UpperCAmelCase_					=	self.model_tester.prepare_config_and_inputs_for_common()

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




						@slow
						def       __a			(       self      :Dict)						->   Union[str, Any]:
												for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		UpperCAmelCase_					=	DPTModel.from_pretrained(_lowercase)
																		self.assertIsNotNone(_lowercase)







def 							A     (						)			->			List[Any]:



						'''simple docstring'''






						UpperCAmelCase_					=	Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
						return image







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

						def       __a			(       self      :List[str])						->   int:
												UpperCAmelCase_					=	DPTImageProcessor.from_pretrained('''Intel/dpt-large''')
												UpperCAmelCase_					=	DPTForDepthEstimation.from_pretrained('''Intel/dpt-large''').to(_lowercase)

												UpperCAmelCase_					=	prepare_img()
												UpperCAmelCase_					=	image_processor(images=_lowercase  ,		return_tensors='''pt''').to(_lowercase)

												# forward pass
												with torch.no_grad():
																		UpperCAmelCase_					=	model(**_lowercase)
																		UpperCAmelCase_					=	outputs.predicted_depth

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

												UpperCAmelCase_					=	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(_lowercase)

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

						def       __a			(       self      :Tuple)						->   Any:
												UpperCAmelCase_					=	DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade''')
												UpperCAmelCase_					=	DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade''').to(_lowercase)

												UpperCAmelCase_					=	prepare_img()
												UpperCAmelCase_					=	image_processor(images=_lowercase  ,		return_tensors='''pt''').to(_lowercase)

												# forward pass
												with torch.no_grad():
																		UpperCAmelCase_					=	model(**_lowercase)

												# verify the logits
												UpperCAmelCase_					=	torch.Size((1, 150, 480, 480))
												self.assertEqual(outputs.logits.shape  ,		_lowercase)

												UpperCAmelCase_					=	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(_lowercase)

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




						def       __a			(       self      :List[str])						->   int:
												UpperCAmelCase_					=	DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade''')
												UpperCAmelCase_					=	DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade''').to(_lowercase)

												UpperCAmelCase_					=	prepare_img()
												UpperCAmelCase_					=	image_processor(images=_lowercase  ,		return_tensors='''pt''').to(_lowercase)

												# forward pass
												with torch.no_grad():
																		UpperCAmelCase_					=	model(**_lowercase)

												UpperCAmelCase_					=	outputs.logits.detach().cpu()

												UpperCAmelCase_					=	image_processor.post_process_semantic_segmentation(outputs=_lowercase  ,		target_sizes=[(500, 300)])
												UpperCAmelCase_					=	torch.Size((500, 300))
												self.assertEqual(segmentation[0].shape  ,		_lowercase)

												UpperCAmelCase_					=	image_processor.post_process_semantic_segmentation(outputs=_lowercase)
												UpperCAmelCase_					=	torch.Size((480, 480))
												self.assertEqual(segmentation[0].shape  ,		_lowercase)










import json

import requests

from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info







def 							A     (						__UpperCAmelCase      )			->			Dict:



						'''simple docstring'''






						class 				a_    :

												def __init__(       self      :Optional[int]  ,		_lowercase      :Any)						->   None:
																		assert isinstance(_lowercase  ,		(bytes, str))
																		UpperCAmelCase_					=	content




												def       __a			(       self      :List[str])						->   Tuple:
																		return json.loads(self.content)

						def mock_response(*__UpperCAmelCase				,   **__UpperCAmelCase      ):
												assert args[0] == AUTHENTICATED_USER_ENDPOINT
												assert "Authorization" in kwargs["headers"]
												assert kwargs["headers"]["Authorization"].startswith('''token '''      )
												assert "Accept" in kwargs["headers"]
												return FakeResponse(b'''{"login":"test","id":1}'''      )

						monkeypatch.setattr(__UpperCAmelCase				,   '''get'''				,   __UpperCAmelCase      )
						UpperCAmelCase_					=	fetch_github_info('''token'''      )
						assert result["login"] == "test"
						assert result["id"] == 1





