



"""simple docstring"""

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



						def __init__(self    ,  _lowercase    ,  _lowercase=2    ,  _lowercase=32    ,  _lowercase=16    ,  _lowercase=3    ,  _lowercase=True    ,  _lowercase=True    ,  _lowercase=32    ,  _lowercase=4    ,  _lowercase=[0, 1, 2, 3]    ,  _lowercase=4    ,  _lowercase=37    ,  _lowercase="gelu"    ,  _lowercase=0.1    ,  _lowercase=0.1    ,  _lowercase=0.02    ,  _lowercase=3    ,  _lowercase=[1, 384, 24, 24]    ,  _lowercase=True    ,  _lowercase=None    ,  ):





													'''simple docstring'''

													__a		:		Union[str, Any]						=							parent
													__a		:		List[str]						=							batch_size
													__a		:		Optional[Any]						=							image_size
													__a		:		Optional[int]						=							patch_size
													__a		:		List[str]						=							num_channels
													__a		:		List[Any]						=							is_training
													__a		:		Optional[Any]						=							use_labels
													__a		:		Dict						=							hidden_size
													__a		:		Union[str, Any]						=							num_hidden_layers
													__a		:		Union[str, Any]						=							backbone_out_indices
													__a		:		int						=							num_attention_heads
													__a		:		Any						=							intermediate_size
													__a		:		Optional[Any]						=							hidden_act
													__a		:		List[str]						=							hidden_dropout_prob
													__a		:		Union[str, Any]						=							attention_probs_dropout_prob
													__a		:		Any						=							initializer_range
													__a		:		List[Any]						=							num_labels
													__a		:		int						=							backbone_featmap_shape
													__a		:		Tuple						=							scope
													__a		:		List[Any]						=							is_hybrid
													# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
													__a		:		int						=							(image_size // patch_size) ** 2
													__a		:		Union[str, Any]						=							num_patches + 1



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		List[Any]						=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

													__a		:		List[Any]						=							None
													if self.use_labels:
																				__a		:		Union[str, Any]						=							ids_tensor([self.batch_size, self.image_size, self.image_size]    ,  self.num_labels				)

													__a		:		List[str]						=							self.get_config()

													return config, pixel_values, labels



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		Tuple						=							{
													    """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=a__    ,  initializer_range=self.initializer_range    ,  is_hybrid=self.is_hybrid    ,  backbone_config=a__    ,  backbone_featmap_shape=self.backbone_featmap_shape    ,  )



						def      lowerCAmelCase__(self    ,  _lowercase    ,  _lowercase    ,  _lowercase				):





													'''simple docstring'''

													__a		:		Tuple						=							DPTModel(config=a__				)
													model.to(a__				)
													model.eval()
													__a		:		int						=							model(a__				)
													self.parent.assertEqual(result.last_hidden_state.shape    ,  (self.batch_size, self.seq_length, self.hidden_size)				)



						def      lowerCAmelCase__(self    ,  _lowercase    ,  _lowercase    ,  _lowercase				):





													'''simple docstring'''

													__a		:		Optional[Any]						=							self.num_labels
													__a		:		Any						=							DPTForDepthEstimation(a__				)
													model.to(a__				)
													model.eval()
													__a		:		int						=							model(a__				)
													self.parent.assertEqual(result.predicted_depth.shape    ,  (self.batch_size, self.image_size, self.image_size)				)



						def      lowerCAmelCase__(self    ,  _lowercase    ,  _lowercase    ,  _lowercase				):





													'''simple docstring'''

													__a		:		Optional[int]						=							self.num_labels
													__a		:		List[str]						=							DPTForSemanticSegmentation(a__				)
													model.to(a__				)
													model.eval()
													__a		:		Optional[int]						=							model(a__    ,  labels=a__				)
													self.parent.assertEqual(
													    result.logits.shape    ,  (self.batch_size, self.num_labels, self.image_size, self.image_size)				)





						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		Tuple						=							self.prepare_config_and_inputs()
													__a		:		Tuple						=							config_and_inputs
													__a		:		Union[str, Any]						=							{"""pixel_values""": pixel_values}
													return config, inputs_dict







@require_torch
class SCREAMING_SNAKE_CASE__       (		lowercase_  ,       lowercase_  ,       unittest.TestCase   ):
						_lowerCAmelCase    						=       (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
						_lowerCAmelCase    						=       (
						    {
						        "depth-estimation": DPTForDepthEstimation,
						        "feature-extraction": DPTModel,
						        "image-segmentation": DPTForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						_lowerCAmelCase    						=       False
						_lowerCAmelCase    						=       False
						_lowerCAmelCase    						=       False



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		Any						=							DPTModelTester(self				)
													__a		:		Dict						=							ConfigTester(self    ,  config_class=a__    ,  has_text_modality=a__    ,  hidden_size=37				)



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													self.config_tester.run_common_tests()



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





													'''simple docstring'''

													pass



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		Union[str, Any]						=							self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				__a		:		List[Any]						=							model_class(a__				)
																				self.assertIsInstance(model.get_input_embeddings()    ,  (nn.Module)				)
																				__a		:		int						=							model.get_output_embeddings()
																				self.assertTrue(x is None or isinstance(a__    ,  nn.Linear				)				)



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		Union[str, Any]						=							self.model_tester.prepare_config_and_inputs_for_common()

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

																				__a		:		Optional[int]						=							["""pixel_values"""]
																				self.assertListEqual(arg_names[:1]    ,  a__				)



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		Any						=							self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*a__				)



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		int						=							self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_depth_estimation(*a__				)



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		Union[str, Any]						=							self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_semantic_segmentation(*a__				)



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

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

																				__a		:		str						=							self.model_tester.prepare_config_and_inputs_for_common()
																				__a		:		Optional[Any]						=							True

																				if model_class in get_values(a__				):
																											continue

																				__a		:		int						=							model_class(a__				)
																				model.to(a__				)
																				model.train()
																				__a		:		Optional[Any]						=							self._prepare_for_class(a__    ,  a__    ,  return_labels=a__				)
																				__a		:		Optional[Any]						=							model(**a__				).loss
																				loss.backward()



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

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

																				__a		:		Any						=							self.model_tester.prepare_config_and_inputs_for_common()
																				__a		:		List[Any]						=							False
																				__a		:		Union[str, Any]						=							True

																				if model_class in get_values(a__				) or not model_class.supports_gradient_checkpointing:
																											continue
																				__a		:		str						=							model_class(a__				)
																				model.to(a__				)
																				model.gradient_checkpointing_enable()
																				model.train()
																				__a		:		List[Any]						=							self._prepare_for_class(a__    ,  a__    ,  return_labels=a__				)
																				__a		:		str						=							model(**a__				).loss
																				loss.backward()



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		int						=							self.model_tester.prepare_config_and_inputs_for_common()

													__a		:		Union[str, Any]						=							_config_zero_init(a__				)
													for model_class in self.all_model_classes:
																				__a		:		List[Any]						=							model_class(config=a__				)
																				# Skip the check for the backbone
																				__a		:		str						=							[]
																				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      lowerCAmelCase__(self				):





													'''simple docstring'''

													pass



						@slow
						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
																				__a		:		Optional[int]						=							DPTModel.from_pretrained(a__				)
																				self.assertIsNotNone(a__				)





						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		int						=							self.model_tester.prepare_config_and_inputs_for_common()
													__a		:		Dict						=							"""add"""
													with self.assertRaises(a__				):
																				__a		:		Optional[int]						=							DPTForDepthEstimation(a__				)







def    __magic_name__     ( ):
							__a		:		Optional[int]						=							Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""       )
							return image







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



						def      lowerCAmelCase__(self				):





													'''simple docstring'''

													__a		:		Optional[Any]						=							DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas"""				)
													__a		:		Any						=							DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas"""				).to(a__				)

													__a		:		str						=							prepare_img()
													__a		:		List[Any]						=							image_processor(images=a__    ,  return_tensors="""pt"""				).to(a__				)

													# forward pass
													with torch.no_grad():
																				__a		:		List[str]						=							model(**a__				)
																				__a		:		List[str]						=							outputs.predicted_depth

													# verify the predicted depth
													__a		:		Optional[int]						=							torch.Size((1, 384, 384)				)
													self.assertEqual(predicted_depth.shape    ,  a__				)

													__a		:		Tuple						=							torch.tensor(
													    [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]]				).to(a__				)

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









import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict

from ..features import Audio, ClassLabel, Features
from .base import TaskTemplate




@dataclass(frozen=lowercase_)
class       snake_case__ (				lowercase_):

       '''simple docstring'''
       lowerCamelCase				:					str								=			field(default="audio-classification"						,     metadata={"include_in_asdict_even_if_is_default": True})
       lowerCamelCase				:					ClassVar[Features]								=			Features({"audio": Audio()})
       lowerCamelCase				:					ClassVar[Features]								=			Features({"labels": ClassLabel})
       lowerCamelCase				:					str								=			"audio"
       lowerCamelCase				:					str								=			"labels"



       def        __lowercase    (				self      ,    a__     )			->   Dict:






            '''simple docstring'''





            if self.label_column not in features:
                 raise ValueError(F'''Column {self.label_column} is not present in features.'''     )
            if not isinstance(features[self.label_column]      ,    a__     ):
                 raise ValueError(F'''Column {self.label_column} is not a ClassLabel.'''     )
            __snake_case      :Any 							=    copy.deepcopy(self     )
            __snake_case      :List[Any] 							=    self.label_schema.copy()
            __snake_case      :List[Any] 							=    features[self.label_column]
            __snake_case      :Optional[Any] 							=    label_schema
            return task_template



       @property
       def        __lowercase    (				self     )			->   Dict[str, str]:






            '''simple docstring'''





            return {
                self.audio_column: "audio",
                self.label_column: "labels",
            }


