

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    ,						__UpperCAmelCase    ,						__UpperCAmelCase=2    ,						__UpperCAmelCase=32    ,						__UpperCAmelCase=16    ,						__UpperCAmelCase=3    ,						__UpperCAmelCase=True    ,						__UpperCAmelCase=True    ,						__UpperCAmelCase=32    ,						__UpperCAmelCase=4    ,						__UpperCAmelCase=[0, 1, 2, 3]    ,						__UpperCAmelCase=4    ,						__UpperCAmelCase=37    ,						__UpperCAmelCase="gelu"    ,						__UpperCAmelCase=0.1    ,						__UpperCAmelCase=0.1    ,						__UpperCAmelCase=0.0_2    ,						__UpperCAmelCase=3    ,						__UpperCAmelCase=[1, 3_84, 24, 24]    ,						__UpperCAmelCase=True    ,						__UpperCAmelCase=None    ,						)		->       Union[str, Any]:
														A      :					List[str]      		=					parent
														A      :					Union[str, Any]      		=					batch_size
														A      :					str      		=					image_size
														A      :					List[str]      		=					patch_size
														A      :					Tuple      		=					num_channels
														A      :					List[str]      		=					is_training
														A      :					Any      		=					use_labels
														A      :					List[str]      		=					hidden_size
														A      :					List[Any]      		=					num_hidden_layers
														A      :					List[Any]      		=					backbone_out_indices
														A      :					Tuple      		=					num_attention_heads
														A      :					Tuple      		=					intermediate_size
														A      :					List[str]      		=					hidden_act
														A      :					Optional[Any]      		=					hidden_dropout_prob
														A      :					Optional[Any]      		=					attention_probs_dropout_prob
														A      :					List[str]      		=					initializer_range
														A      :					Optional[int]      		=					num_labels
														A      :					Dict      		=					backbone_featmap_shape
														A      :					Any      		=					scope
														A      :					Any      		=					is_hybrid
														# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
														A      :					Optional[int]      		=					(image_size // patch_size) ** 2
														A      :					int      		=					num_patches + 1




							def       snake_case			(					self						)		->       Any:
														A      :					int      		=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

														A      :					Tuple      		=					None
														if self.use_labels:
																					A      :					List[Any]      		=					ids_tensor([self.batch_size, self.image_size, self.image_size]    ,						self.num_labels						)

														A      :					Tuple      		=					self.get_config()

														return config, pixel_values, labels




							def       snake_case			(					self						)		->       Optional[Any]:
														A      :					Optional[int]      		=					{
														    '''global_padding''': '''same''',
														    '''layer_type''': '''bottleneck''',
														    '''depths''': [3, 4, 9],
														    '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
														    '''embedding_dynamic_padding''': True,
														    '''hidden_sizes''': [96, 1_92, 3_84, 7_68],
														    '''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       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase						)		->       int:
														A      :					Optional[Any]      		=					DPTModel(config=__UpperCAmelCase						)
														model.to(__UpperCAmelCase						)
														model.eval()
														A      :					Tuple      		=					model(__UpperCAmelCase						)
														self.parent.assertEqual(result.last_hidden_state.shape    ,						(self.batch_size, self.seq_length, self.hidden_size)						)




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase						)		->       Optional[int]:
														A      :					Optional[int]      		=					self.num_labels
														A      :					Any      		=					DPTForDepthEstimation(__UpperCAmelCase						)
														model.to(__UpperCAmelCase						)
														model.eval()
														A      :					str      		=					model(__UpperCAmelCase						)
														self.parent.assertEqual(result.predicted_depth.shape    ,						(self.batch_size, self.image_size, self.image_size)						)




							def       snake_case			(					self    ,						__UpperCAmelCase    ,						__UpperCAmelCase    ,						__UpperCAmelCase						)		->       Optional[int]:
														A      :					str      		=					self.num_labels
														A      :					Optional[int]      		=					DPTForSemanticSegmentation(__UpperCAmelCase						)
														model.to(__UpperCAmelCase						)
														model.eval()
														A      :					List[Any]      		=					model(__UpperCAmelCase    ,						labels=__UpperCAmelCase						)
														self.parent.assertEqual(
														    result.logits.shape    ,						(self.batch_size, self.num_labels, self.image_size, self.image_size)						)






							def       snake_case			(					self						)		->       Any:
														A      :					List[Any]      		=					self.prepare_config_and_inputs()
														A		,		A		,		A      :					Optional[Any]      		=					config_and_inputs
														A      :					List[Any]      		=					{'''pixel_values''': pixel_values}
														return config, inputs_dict







@require_torch
class 					__lowercase  (						_SCREAMING_SNAKE_CASE		,       _SCREAMING_SNAKE_CASE		,       unittest.TestCase				):





							"""simple docstring"""

							UpperCAmelCase_						:		str								=	(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_						:		Any								=	False
							UpperCAmelCase_						:		int								=	False
							UpperCAmelCase_						:		Optional[Any]								=	False




							def       snake_case			(					self						)		->       Tuple:
														A      :					int      		=					DPTModelTester(self						)
														A      :					List[Any]      		=					ConfigTester(self    ,						config_class=__UpperCAmelCase    ,						has_text_modality=__UpperCAmelCase    ,						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						)		->       List[str]:
														pass




							def       snake_case			(					self						)		->       int:
														A		,		A      :					Dict      		=					self.model_tester.prepare_config_and_inputs_for_common()

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




							def       snake_case			(					self						)		->       List[Any]:
														A		,		A      :					Any      		=					self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					A      :					str      		=					model_class(__UpperCAmelCase						)
																					A      :					Optional[Any]      		=					inspect.signature(model.forward						)
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					A      :					int      		=					[*signature.parameters.keys()]

																					A      :					Optional[int]      		=					['''pixel_values''']
																					self.assertListEqual(arg_names[:1]    ,						__UpperCAmelCase						)




							def       snake_case			(					self						)		->       Optional[int]:
														A      :					Union[str, Any]      		=					self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*__UpperCAmelCase						)




							def       snake_case			(					self						)		->       Union[str, Any]:
														A      :					Optional[int]      		=					self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_depth_estimation(*__UpperCAmelCase						)




							def       snake_case			(					self						)		->       Tuple:
														A      :					List[Any]      		=					self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCAmelCase						)




							def       snake_case			(					self						)		->       Union[str, Any]:
														for model_class in self.all_model_classes:
																					if model_class.__name__ == "DPTForDepthEstimation":
																												continue

																					A		,		A      :					str      		=					self.model_tester.prepare_config_and_inputs_for_common()
																					A      :					Optional[int]      		=					True

																					if model_class in get_values(__UpperCAmelCase						):
																												continue

																					A      :					Any      		=					model_class(__UpperCAmelCase						)
																					model.to(__UpperCAmelCase						)
																					model.train()
																					A      :					Tuple      		=					self._prepare_for_class(__UpperCAmelCase    ,						__UpperCAmelCase    ,						return_labels=__UpperCAmelCase						)
																					A      :					Union[str, Any]      		=					model(**__UpperCAmelCase						).loss
																					loss.backward()




							def       snake_case			(					self						)		->       List[Any]:
														for model_class in self.all_model_classes:
																					if model_class.__name__ == "DPTForDepthEstimation":
																												continue

																					A		,		A      :					int      		=					self.model_tester.prepare_config_and_inputs_for_common()
																					A      :					Optional[int]      		=					False
																					A      :					Optional[Any]      		=					True

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




							def       snake_case			(					self						)		->       int:
														A		,		A      :					Optional[int]      		=					self.model_tester.prepare_config_and_inputs_for_common()

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




							@slow
							def       snake_case			(					self						)		->       Dict:
														for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
																					A      :					Tuple      		=					DPTModel.from_pretrained(__UpperCAmelCase						)
																					self.assertIsNotNone(__UpperCAmelCase						)






							def       snake_case			(					self						)		->       Dict:
														# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
														A		,		A      :					str      		=					self.model_tester.prepare_config_and_inputs_for_common()
														A      :					Dict      		=					'''add'''
														with self.assertRaises(__UpperCAmelCase						):
																					A      :					str      		=					DPTForDepthEstimation(__UpperCAmelCase						)






def        snake_case__		(    ):
							A      :					List[Any]      		=					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
							return image







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





							"""simple docstring"""

							def       snake_case			(					self						)		->       Any:
														A      :					str      		=					DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas'''						)
														A      :					Optional[Any]      		=					DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas'''						).to(__UpperCAmelCase						)

														A      :					List[Any]      		=					prepare_img()
														A      :					str      		=					image_processor(images=__UpperCAmelCase    ,						return_tensors='''pt'''						).to(__UpperCAmelCase						)

														# forward pass
														with torch.no_grad():
																					A      :					int      		=					model(**__UpperCAmelCase						)
																					A      :					Dict      		=					outputs.predicted_depth

														# verify the predicted depth
														A      :					int      		=					torch.Size((1, 3_84, 3_84)						)
														self.assertEqual(predicted_depth.shape    ,						__UpperCAmelCase						)

														A      :					List[Any]      		=					torch.tensor(
														    [[[5.6_4_3_7, 5.6_1_4_6, 5.6_5_1_1], [5.4_3_7_1, 5.5_6_4_9, 5.5_9_5_8], [5.5_2_1_5, 5.5_1_8_4, 5.5_2_9_3]]]						).to(__UpperCAmelCase						)

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









import os
import unittest

from huggingface_hub.utils import are_progress_bars_disabled

import transformers.models.bart.tokenization_bart
from transformers import logging
from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context
from transformers.utils.logging import disable_progress_bar, enable_progress_bar







class 					__lowercase  (						unittest.TestCase				):





							"""simple docstring"""

							def       snake_case			(					self						)		->       Union[str, Any]:
														A      :					Dict      		=					logging.get_logger()

														# the current default level is logging.WARNING
														A      :					List[Any]      		=					logging.get_verbosity()

														logging.set_verbosity_error()
														self.assertEqual(logger.getEffectiveLevel()    ,						logging.get_verbosity()						)

														logging.set_verbosity_warning()
														self.assertEqual(logger.getEffectiveLevel()    ,						logging.get_verbosity()						)

														logging.set_verbosity_info()
														self.assertEqual(logger.getEffectiveLevel()    ,						logging.get_verbosity()						)

														logging.set_verbosity_debug()
														self.assertEqual(logger.getEffectiveLevel()    ,						logging.get_verbosity()						)

														# restore to the original level
														logging.set_verbosity(__UpperCAmelCase						)




							def       snake_case			(					self						)		->       str:
														A      :					Any      		=					logging.get_verbosity()

														A      :					Optional[Any]      		=					logging.get_logger('''transformers.models.bart.tokenization_bart'''						)
														A      :					Tuple      		=					'''Testing 1, 2, 3'''

														# should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`)
														if level_origin <= logging.WARNING:
																					with CaptureLogger(__UpperCAmelCase						) as cl:
																												logger.warning(__UpperCAmelCase						)
																					self.assertEqual(cl.out    ,						msg + '''\n'''						)

														# this is setting the level for all of `transformers.*` loggers
														logging.set_verbosity_error()

														# should not be able to log warnings
														with CaptureLogger(__UpperCAmelCase						) as cl:
																					logger.warning(__UpperCAmelCase						)
														self.assertEqual(cl.out    ,						''''''						)

														# should be able to log warnings again
														logging.set_verbosity_warning()
														with CaptureLogger(__UpperCAmelCase						) as cl:
																					logger.warning(__UpperCAmelCase						)
														self.assertEqual(cl.out    ,						msg + '''\n'''						)

														# restore to the original level
														logging.set_verbosity(__UpperCAmelCase						)




							@mockenv(TRANSFORMERS_VERBOSITY='''error'''						)
							def       snake_case			(					self						)		->       Optional[int]:
														# reset for the env var to take effect, next time some logger call is made
														transformers.utils.logging._reset_library_root_logger()
														# this action activates the env var
														A      :					int      		=					logging.get_logger('''transformers.models.bart.tokenization_bart'''						)

														A      :					Any      		=					os.getenv('''TRANSFORMERS_VERBOSITY'''    ,						__UpperCAmelCase						)
														A      :					List[str]      		=					logging.log_levels[env_level_str]

														A      :					Optional[int]      		=					logging.get_verbosity()
														self.assertEqual(
														    __UpperCAmelCase    ,						__UpperCAmelCase    ,						f'TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}'    ,						)

														# restore to the original level
														A      :					str      		=					''''''
														transformers.utils.logging._reset_library_root_logger()




							@mockenv(TRANSFORMERS_VERBOSITY='''super-error'''						)
							def       snake_case			(					self						)		->       Optional[int]:
														# reset for the env var to take effect, next time some logger call is made
														transformers.utils.logging._reset_library_root_logger()
														A      :					str      		=					logging.logging.getLogger()
														with CaptureLogger(__UpperCAmelCase						) as cl:
																					# this action activates the env var
																					logging.get_logger('''transformers.models.bart.tokenization_bart'''						)
														self.assertIn('''Unknown option TRANSFORMERS_VERBOSITY=super-error'''    ,						cl.out						)

														# no need to restore as nothing was changed






							def       snake_case			(					self						)		->       Optional[int]:
														# testing `logger.warning_advice()`
														transformers.utils.logging._reset_library_root_logger()

														A      :					Union[str, Any]      		=					logging.get_logger('''transformers.models.bart.tokenization_bart'''						)
														A      :					Optional[int]      		=					'''Testing 1, 2, 3'''

														with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS='''1'''						):
																					# nothing should be logged as env var disables this method
																					with CaptureLogger(__UpperCAmelCase						) as cl:
																												logger.warning_advice(__UpperCAmelCase						)
																					self.assertEqual(cl.out    ,						''''''						)

														with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=''''''						):
																					# should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset
																					with CaptureLogger(__UpperCAmelCase						) as cl:
																												logger.warning_advice(__UpperCAmelCase						)
																					self.assertEqual(cl.out    ,						msg + '''\n'''						)






def        snake_case__		(    ):
							disable_progress_bar()
							assert are_progress_bars_disabled()

							enable_progress_bar()
							assert not are_progress_bars_disabled()






