


from typing import Optional, Union

from ...file_utils import TensorType
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, TruncationStrategy



class    __lowercase  (       UpperCamelCase							):

							"""simple docstring"""


							SCREAMING_SNAKE_CASE   :					Tuple        =						"MarkupLMFeatureExtractor"
							SCREAMING_SNAKE_CASE   :					Optional[Any]        =						("MarkupLMTokenizer", "MarkupLMTokenizerFast")
							SCREAMING_SNAKE_CASE   :					str        =						True





							def __call__(    self				, A_=None				, A_=None				, A_=None				, A_=None				, A_=None				, A_ = True				, A_ = False				, A_ = None				, A_ = None				, A_ = 0				, A_ = None				, A_ = None				, A_ = None				, A_ = False				, A_ = False				, A_ = False				, A_ = False				, A_ = True				, A_ = None				, **A_				, )->	BatchEncoding:
											# first, create nodes and xpaths
											if self.parse_html:
															if html_strings is None:
																			raise ValueError('Make sure to pass HTML strings in case `parse_html` is set to `True`'	)

															if nodes is not None or xpaths is not None or node_labels is not None:
																			raise ValueError(
																			    'Please don\'t pass nodes, xpaths nor node labels in case `parse_html` is set to `True`'	)

															_SCREAMING_SNAKE_CASE      = self.feature_extractor(A_	)
															_SCREAMING_SNAKE_CASE      = features['nodes']
															_SCREAMING_SNAKE_CASE      = features['xpaths']
											else:
															if html_strings is not None:
																			raise ValueError('You have passed HTML strings but `parse_html` is set to `False`.'	)
															if nodes is None or xpaths is None:
																			raise ValueError('Make sure to pass nodes and xpaths in case `parse_html` is set to `False`'	)

        # # second, apply the tokenizer
											if questions is not None and self.parse_html:
															if isinstance(A_				, A_	):
																			_SCREAMING_SNAKE_CASE      = [questions]  # add batch dimension (as the feature extractor always adds a batch dimension)

											_SCREAMING_SNAKE_CASE      = self.tokenizer(
											    text=questions if questions is not None else nodes				, text_pair=nodes if questions is not None else None				, xpaths=A_				, node_labels=A_				, add_special_tokens=A_				, padding=A_				, truncation=A_				, max_length=A_				, stride=A_				, pad_to_multiple_of=A_				, return_token_type_ids=A_				, return_attention_mask=A_				, return_overflowing_tokens=A_				, return_special_tokens_mask=A_				, return_offsets_mapping=A_				, return_length=A_				, verbose=A_				, return_tensors=A_				, **A_				, )

											return encoded_inputs





							def 		__magic_name__			(    self				, *A_				, **A_	)->	Optional[Any]:
											return self.tokenizer.batch_decode(*A_				, **A_	)





							def 		__magic_name__			(    self				, *A_				, **A_	)->	Tuple:
											return self.tokenizer.decode(*A_				, **A_	)





							@property
							def 		__magic_name__			(    self	)->	Tuple:
											_SCREAMING_SNAKE_CASE      = self.tokenizer.model_input_names
											return tokenizer_input_names




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

							"""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				, )->	int:
											_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      = 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 		__magic_name__			(    self	)->	Optional[Any]:
											_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 		__magic_name__			(    self	)->	Optional[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 		__magic_name__			(    self				, A_				, A_				, A_	)->	List[Any]:
											_SCREAMING_SNAKE_CASE      = DPTModel(config=A_	)
											model.to(A_	)
											model.eval()
											_SCREAMING_SNAKE_CASE      = model(A_	)
											self.parent.assertEqual(result.last_hidden_state.shape				, (self.batch_size, self.seq_length, self.hidden_size)	)





							def 		__magic_name__			(    self				, A_				, A_				, A_	)->	Tuple:
											_SCREAMING_SNAKE_CASE      = self.num_labels
											_SCREAMING_SNAKE_CASE      = DPTForDepthEstimation(A_	)
											model.to(A_	)
											model.eval()
											_SCREAMING_SNAKE_CASE      = model(A_	)
											self.parent.assertEqual(result.predicted_depth.shape				, (self.batch_size, self.image_size, self.image_size)	)





							def 		__magic_name__			(    self				, A_				, A_				, A_	)->	str:
											_SCREAMING_SNAKE_CASE      = self.num_labels
											_SCREAMING_SNAKE_CASE      = DPTForSemanticSegmentation(A_	)
											model.to(A_	)
											model.eval()
											_SCREAMING_SNAKE_CASE      = model(A_				, labels=A_	)
											self.parent.assertEqual(
											    result.logits.shape				, (self.batch_size, self.num_labels, self.image_size, self.image_size)	)





							def 		__magic_name__			(    self	)->	str:
											_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    __lowercase  (       UpperCamelCase      ,     UpperCamelCase      ,     unittest.TestCase							):

							"""simple docstring"""


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

							SCREAMING_SNAKE_CASE   :					Tuple        =						False
							SCREAMING_SNAKE_CASE   :					str        =						False
							SCREAMING_SNAKE_CASE   :					Dict        =						False





							def 		__magic_name__			(    self	)->	List[str]:
											_SCREAMING_SNAKE_CASE      = DPTModelTester(self	)
											_SCREAMING_SNAKE_CASE      = ConfigTester(self				, config_class=A_				, has_text_modality=A_				, hidden_size=37	)





							def 		__magic_name__			(    self	)->	str:
											self.config_tester.run_common_tests()





							@unittest.skip(reason='DPT does not use inputs_embeds'	)
							def 		__magic_name__			(    self	)->	Optional[Any]:
											pass





							def 		__magic_name__			(    self	)->	int:
											_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(A_	)
															self.assertIsInstance(model.get_input_embeddings()				, (nn.Module)	)
															_SCREAMING_SNAKE_CASE      = model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(A_				, nn.Linear	)	)





							def 		__magic_name__			(    self	)->	Any:
											_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(A_	)
															_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]				, A_	)





							def 		__magic_name__			(    self	)->	Union[str, Any]:
											_SCREAMING_SNAKE_CASE      = self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*A_	)





							def 		__magic_name__			(    self	)->	str:
											_SCREAMING_SNAKE_CASE      = self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_depth_estimation(*A_	)





							def 		__magic_name__			(    self	)->	Any:
											_SCREAMING_SNAKE_CASE      = self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*A_	)





							def 		__magic_name__			(    self	)->	List[Any]:
											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(A_	):
																			continue

															_SCREAMING_SNAKE_CASE      = model_class(A_	)
															model.to(A_	)
															model.train()
															_SCREAMING_SNAKE_CASE      = self._prepare_for_class(A_				, A_				, return_labels=A_	)
															_SCREAMING_SNAKE_CASE      = model(**A_	).loss
															loss.backward()





							def 		__magic_name__			(    self	)->	Any:
											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(A_	) or not model_class.supports_gradient_checkpointing:
																			continue
															_SCREAMING_SNAKE_CASE      = model_class(A_	)
															model.to(A_	)
															model.gradient_checkpointing_enable()
															model.train()
															_SCREAMING_SNAKE_CASE      = self._prepare_for_class(A_				, A_				, return_labels=A_	)
															_SCREAMING_SNAKE_CASE      = model(**A_	).loss
															loss.backward()





							def 		__magic_name__			(    self	)->	str:
											_SCREAMING_SNAKE_CASE      ,      _SCREAMING_SNAKE_CASE      = self.model_tester.prepare_config_and_inputs_for_common()

											_SCREAMING_SNAKE_CASE      = _config_zero_init(A_	)
											for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE      = model_class(config=A_	)
															# 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 		__magic_name__			(    self	)->	List[Any]:
											pass





							@slow
							def 		__magic_name__			(    self	)->	Optional[int]:
											for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE      = DPTModel.from_pretrained(A_	)
															self.assertIsNotNone(A_	)







def 				SCREAMING_SNAKE_CASE (     ):

				"""simple docstring"""






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



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

							"""simple docstring"""


							def 		__magic_name__			(    self	)->	Optional[Any]:
											_SCREAMING_SNAKE_CASE      = DPTImageProcessor.from_pretrained('Intel/dpt-large'	)
											_SCREAMING_SNAKE_CASE      = DPTForDepthEstimation.from_pretrained('Intel/dpt-large'	).to(A_	)

											_SCREAMING_SNAKE_CASE      = prepare_img()
											_SCREAMING_SNAKE_CASE      = image_processor(images=A_				, return_tensors='pt'	).to(A_	)

											# forward pass
											with torch.no_grad():
															_SCREAMING_SNAKE_CASE      = model(**A_	)
															_SCREAMING_SNAKE_CASE      = outputs.predicted_depth

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

											_SCREAMING_SNAKE_CASE      = torch.tensor(
											    [[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]]	).to(A_	)

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





							def 		__magic_name__			(    self	)->	Optional[Any]:
											_SCREAMING_SNAKE_CASE      = DPTImageProcessor.from_pretrained('Intel/dpt-large-ade'	)
											_SCREAMING_SNAKE_CASE      = DPTForSemanticSegmentation.from_pretrained('Intel/dpt-large-ade'	).to(A_	)

											_SCREAMING_SNAKE_CASE      = prepare_img()
											_SCREAMING_SNAKE_CASE      = image_processor(images=A_				, return_tensors='pt'	).to(A_	)

											# forward pass
											with torch.no_grad():
															_SCREAMING_SNAKE_CASE      = model(**A_	)

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

											_SCREAMING_SNAKE_CASE      = torch.tensor(
											    [[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]]	).to(A_	)

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





							def 		__magic_name__			(    self	)->	Optional[int]:
											_SCREAMING_SNAKE_CASE      = DPTImageProcessor.from_pretrained('Intel/dpt-large-ade'	)
											_SCREAMING_SNAKE_CASE      = DPTForSemanticSegmentation.from_pretrained('Intel/dpt-large-ade'	).to(A_	)

											_SCREAMING_SNAKE_CASE      = prepare_img()
											_SCREAMING_SNAKE_CASE      = image_processor(images=A_				, return_tensors='pt'	).to(A_	)

											# forward pass
											with torch.no_grad():
															_SCREAMING_SNAKE_CASE      = model(**A_	)

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

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

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