






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						:







			def __init__(      self:    Dict ,      UpperCAmelCase_:    str ,      UpperCAmelCase_:    str=2 ,      UpperCAmelCase_:    List[Any]=32 ,      UpperCAmelCase_:    Union[str, Any]=16 ,      UpperCAmelCase_:    Any=3 ,      UpperCAmelCase_:    Tuple=True ,      UpperCAmelCase_:    List[str]=True ,      UpperCAmelCase_:    List[Any]=32 ,      UpperCAmelCase_:    Dict=4 ,      UpperCAmelCase_:    Optional[Any]=[0, 1, 2, 3] ,      UpperCAmelCase_:    Tuple=4 ,      UpperCAmelCase_:    List[Any]=37 ,      UpperCAmelCase_:    List[str]="gelu" ,      UpperCAmelCase_:    Optional[Any]=0.1 ,      UpperCAmelCase_:    Any=0.1 ,      UpperCAmelCase_:    str=0.02 ,      UpperCAmelCase_:    Optional[int]=3 ,      UpperCAmelCase_:    str=False ,      UpperCAmelCase_:    str=None ,      ):







									'''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       =    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 				UpperCamelCase (      self:    Dict	):







									'''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 				UpperCamelCase (      self:    Optional[int]	):







									'''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=UpperCAmelCase_ ,      initializer_range=self.initializer_range ,      is_hybrid=self.is_hybrid ,      )







			def 				UpperCamelCase (      self:    Any ,      UpperCAmelCase_:    int ,      UpperCAmelCase_:    Dict ,      UpperCAmelCase_:    Union[str, Any]	):







									'''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 				UpperCamelCase (      self:    Optional[int] ,      UpperCAmelCase_:    Dict ,      UpperCAmelCase_:    List[Any] ,      UpperCAmelCase_:    Dict	):







									'''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 				UpperCamelCase (      self:    List[Any] ,      UpperCAmelCase_:    Any ,      UpperCAmelCase_:    List[Any] ,      UpperCAmelCase_:    Optional[int]	):







									'''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 				UpperCamelCase (      self:    List[str]	):







									'''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       ):
			__snake_case							: str							=				(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
			__snake_case							: str							=				(
			    {
			        "depth-estimation": DPTForDepthEstimation,
			        "feature-extraction": DPTModel,
			        "image-segmentation": DPTForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

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







			def 				UpperCamelCase (      self:    Any	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DPTModelTester(self	)
									_SCREAMING_SNAKE_CASE       =    ConfigTester(self ,      config_class=UpperCAmelCase_ ,      has_text_modality=UpperCAmelCase_ ,      hidden_size=37	)







			def 				UpperCamelCase (      self:    List[Any]	):







									'''simple docstring'''




									self.config_tester.run_common_tests()







			@unittest.skip(reason="""DPT does not use inputs_embeds"""	)
			def 				UpperCamelCase (      self:    Dict	):







									'''simple docstring'''




									pass







			def 				UpperCamelCase (      self:    List[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 				UpperCamelCase (      self:    Union[str, 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 				UpperCamelCase (      self:    Any	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*UpperCAmelCase_	)







			def 				UpperCamelCase (      self:    Dict	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_depth_estimation(*UpperCAmelCase_	)







			def 				UpperCamelCase (      self:    List[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_	)







			def 				UpperCamelCase (      self:    Optional[int]	):







									'''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 				UpperCamelCase (      self:    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       =    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 				UpperCamelCase (      self:    int	):







									'''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 				UpperCamelCase (      self:    Union[str, Any]	):







									'''simple docstring'''




									pass







			@slow
			def 				UpperCamelCase (      self:    int	):







									'''simple docstring'''




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

def 			__lowerCamelCase     (						)				->    Tuple:






						"""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       ):







			def 				UpperCamelCase (      self:    Union[str, Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DPTImageProcessor.from_pretrained("""Intel/dpt-large"""	)
									_SCREAMING_SNAKE_CASE       =    DPTForDepthEstimation.from_pretrained("""Intel/dpt-large"""	).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(
									    [[6.31_99, 6.36_29, 6.41_48], [6.38_50, 6.36_15, 6.41_66], [6.35_19, 6.31_76, 6.35_75]]	).to(UpperCAmelCase_	)

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







			def 				UpperCamelCase (      self:    Dict	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DPTImageProcessor.from_pretrained("""Intel/dpt-large-ade"""	)
									_SCREAMING_SNAKE_CASE       =    DPTForSemanticSegmentation.from_pretrained("""Intel/dpt-large-ade"""	).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_	)

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

									_SCREAMING_SNAKE_CASE       =    torch.tensor(
									    [[4.04_80, 4.24_20, 4.43_60], [4.31_24, 4.56_93, 4.82_61], [4.57_68, 4.89_65, 5.21_63]]	).to(UpperCAmelCase_	)

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







			def 				UpperCamelCase (      self:    Optional[Any]	):







									'''simple docstring'''




									_SCREAMING_SNAKE_CASE       =    DPTImageProcessor.from_pretrained("""Intel/dpt-large-ade"""	)
									_SCREAMING_SNAKE_CASE       =    DPTForSemanticSegmentation.from_pretrained("""Intel/dpt-large-ade"""	).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.logits.detach().cpu()

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

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









from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
		if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.27.0''')):
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		from ...utils.dummy_torch_and_transformers_objects import (
		    AudioLDMPipeline,
		)
else:
		from .pipeline_audioldm import AudioLDMPipeline

