



"""simple docstring"""




import warnings
from contextlib import contextmanager

from ....processing_utils import ProcessorMixin






class      UpperCAmelCase_  (    _UpperCamelCase						):
      __SCREAMING_SNAKE_CASE						:       Tuple								=			'MCTCTFeatureExtractor'
      __SCREAMING_SNAKE_CASE						:       Any								=			'AutoTokenizer'



      def __init__(					self					:     Tuple					,     A					:     Dict					,     A					:     Optional[int]						):
           super().__init__(A					,     A						)
           _UpperCAmelCase      :     List[Any]        =   self.feature_extractor
           _UpperCAmelCase      :     Any        =   False



      def __call__(					self					:     Any					,     *A					:     Dict					,     **A					:     Tuple						):
           # For backward compatibility
           if self._in_target_context_manager:
                return self.current_processor(*A					,     **A						)

           if "raw_speech" in kwargs:
                warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."						)
                _UpperCAmelCase      :     int        =   kwargs.pop("raw_speech"						)
           else:
                _UpperCAmelCase      :     List[Any]        =   kwargs.pop("audio"					,     A						)
           _UpperCAmelCase      :     str        =   kwargs.pop("sampling_rate"					,     A						)
           _UpperCAmelCase      :     Union[str, Any]        =   kwargs.pop("text"					,     A						)
           if len(A						) > 0:
                _UpperCAmelCase      :     List[str]        =   args[0]
                _UpperCAmelCase      :     Tuple        =   args[1:]

           if audio is None and text is None:
                raise ValueError("You need to specify either an `audio` or `text` input to process."						)

           if audio is not None:
                _UpperCAmelCase      :     List[Any]        =   self.feature_extractor(A					,     *A					,     sampling_rate=A					,     **A						)
           if text is not None:
                _UpperCAmelCase      :     Optional[int]        =   self.tokenizer(A					,     **A						)

           if text is None:
                return inputs
           elif audio is None:
                return encodings
           else:
                _UpperCAmelCase      :     Union[str, Any]        =   encodings["input_ids"]
                return inputs



      def 						snake_case_ (					self					:     List[Any]					,     *A					:     int					,     **A					:     int						):
           return self.tokenizer.batch_decode(*A					,     **A						)



      def 						snake_case_ (					self					:     Dict					,     *A					:     Dict					,     **A					:     Optional[int]						):
           # For backward compatibility
           if self._in_target_context_manager:
                return self.current_processor.pad(*A					,     **A						)

           _UpperCAmelCase      :     str        =   kwargs.pop("input_features"					,     A						)
           _UpperCAmelCase      :     Optional[int]        =   kwargs.pop("labels"					,     A						)
           if len(A						) > 0:
                _UpperCAmelCase      :     Optional[int]        =   args[0]
                _UpperCAmelCase      :     int        =   args[1:]

           if input_features is not None:
                _UpperCAmelCase      :     Optional[Any]        =   self.feature_extractor.pad(A					,     *A					,     **A						)
           if labels is not None:
                _UpperCAmelCase      :     List[str]        =   self.tokenizer.pad(A					,     **A						)

           if labels is None:
                return input_features
           elif input_features is None:
                return labels
           else:
                _UpperCAmelCase      :     Union[str, Any]        =   labels["input_ids"]
                return input_features



      def 						snake_case_ (					self					:     List[Any]					,     *A					:     List[Any]					,     **A					:     str						):
           return self.tokenizer.decode(*A					,     **A						)



      @contextmanager
      def 						snake_case_ (					self					:     Any						):
           warnings.warn(
               "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
               "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
               "your audio inputs, or in a separate call."						)
           _UpperCAmelCase      :     Dict        =   True
           _UpperCAmelCase      :     List[str]        =   self.tokenizer
           yield
           _UpperCAmelCase      :     List[Any]        =   self.feature_extractor
           _UpperCAmelCase      :     Dict        =   False





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



      def __init__(					self					:     Tuple					,     A					:     str					,     A					:     Dict=2					,     A					:     List[Any]=3_2					,     A					:     Optional[Any]=1_6					,     A					:     Tuple=3					,     A					:     Optional[Any]=True					,     A					:     List[Any]=True					,     A					:     Optional[int]=3_2					,     A					:     Optional[int]=4					,     A					:     Tuple=[0, 1, 2, 3]					,     A					:     Optional[int]=4					,     A					:     Tuple=3_7					,     A					:     List[Any]="gelu"					,     A					:     List[Any]=0.1					,     A					:     List[str]=0.1					,     A					:     Union[str, Any]=0.02					,     A					:     Optional[int]=3					,     A					:     Optional[Any]=[1, 3_8_4, 2_4, 2_4]					,     A					:     Union[str, Any]=True					,     A					:     Any=None					,     ):
           _UpperCAmelCase      :     str        =   parent
           _UpperCAmelCase      :     int        =   batch_size
           _UpperCAmelCase      :     List[str]        =   image_size
           _UpperCAmelCase      :     Tuple        =   patch_size
           _UpperCAmelCase      :     Any        =   num_channels
           _UpperCAmelCase      :     List[str]        =   is_training
           _UpperCAmelCase      :     Optional[Any]        =   use_labels
           _UpperCAmelCase      :     str        =   hidden_size
           _UpperCAmelCase      :     Dict        =   num_hidden_layers
           _UpperCAmelCase      :     List[Any]        =   backbone_out_indices
           _UpperCAmelCase      :     Optional[Any]        =   num_attention_heads
           _UpperCAmelCase      :     Optional[int]        =   intermediate_size
           _UpperCAmelCase      :     str        =   hidden_act
           _UpperCAmelCase      :     int        =   hidden_dropout_prob
           _UpperCAmelCase      :     Any        =   attention_probs_dropout_prob
           _UpperCAmelCase      :     Optional[Any]        =   initializer_range
           _UpperCAmelCase      :     Optional[Any]        =   num_labels
           _UpperCAmelCase      :     Tuple        =   backbone_featmap_shape
           _UpperCAmelCase      :     Optional[Any]        =   scope
           _UpperCAmelCase      :     Union[str, Any]        =   is_hybrid
           # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
           _UpperCAmelCase      :     Optional[int]        =   (image_size // patch_size) ** 2
           _UpperCAmelCase      :     int        =   num_patches + 1



      def 						snake_case_ (					self					:     List[str]						):
           _UpperCAmelCase      :     Tuple        =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

           _UpperCAmelCase      :     Dict        =   None
           if self.use_labels:
                _UpperCAmelCase      :     List[str]        =   ids_tensor([self.batch_size, self.image_size, self.image_size]					,     self.num_labels						)

           _UpperCAmelCase      :     str        =   self.get_config()

           return config, pixel_values, labels



      def 						snake_case_ (					self					:     str						):
           _UpperCAmelCase      :     Tuple        =   {
               "global_padding": "same",
               "layer_type": "bottleneck",
               "depths": [3, 4, 9],
               "out_features": ["stage1", "stage2", "stage3"],
               "embedding_dynamic_padding": True,
               "hidden_sizes": [9_6, 1_9_2, 3_8_4, 7_6_8],
               "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 						snake_case_ (					self					:     Any					,     A					:     Optional[Any]					,     A					:     str					,     A					:     Dict						):
           _UpperCAmelCase      :     List[str]        =   DPTModel(config=A						)
           model.to(A						)
           model.eval()
           _UpperCAmelCase      :     List[str]        =   model(A						)
           self.parent.assertEqual(result.last_hidden_state.shape					,     (self.batch_size, self.seq_length, self.hidden_size)						)



      def 						snake_case_ (					self					:     List[str]					,     A					:     str					,     A					:     Any					,     A					:     List[Any]						):
           _UpperCAmelCase      :     str        =   self.num_labels
           _UpperCAmelCase      :     Any        =   DPTForDepthEstimation(A						)
           model.to(A						)
           model.eval()
           _UpperCAmelCase      :     Optional[int]        =   model(A						)
           self.parent.assertEqual(result.predicted_depth.shape					,     (self.batch_size, self.image_size, self.image_size)						)



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



      def 						snake_case_ (					self					:     Union[str, Any]						):
           _UpperCAmelCase      :     Union[str, Any]        =   self.prepare_config_and_inputs()
           _UpperCAmelCase    ,	_UpperCAmelCase    ,	_UpperCAmelCase      :     Dict        =   config_and_inputs
           _UpperCAmelCase      :     int        =   {"pixel_values": pixel_values}
           return config, inputs_dict







@require_torch
class      UpperCAmelCase_  (    _UpperCamelCase	,      _UpperCamelCase	,      unittest.TestCase						):
      __SCREAMING_SNAKE_CASE						:       List[str]								=			(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						:       Dict								=			False
      __SCREAMING_SNAKE_CASE						:       Optional[int]								=			False
      __SCREAMING_SNAKE_CASE						:       Optional[Any]								=			False



      def 						snake_case_ (					self					:     int						):
           _UpperCAmelCase      :     List[str]        =   DPTModelTester(self						)
           _UpperCAmelCase      :     Union[str, Any]        =   ConfigTester(self					,     config_class=A					,     has_text_modality=A					,     hidden_size=3_7						)



      def 						snake_case_ (					self					:     int						):
           self.config_tester.run_common_tests()



      @unittest.skip(reason="DPT does not use inputs_embeds"						)
      def 						snake_case_ (					self					:     Union[str, Any]						):
           pass



      def 						snake_case_ (					self					:     Tuple						):
           _UpperCAmelCase    ,	_UpperCAmelCase      :     List[Any]        =   self.model_tester.prepare_config_and_inputs_for_common()

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



      def 						snake_case_ (					self					:     Optional[Any]						):
           _UpperCAmelCase    ,	_UpperCAmelCase      :     List[str]        =   self.model_tester.prepare_config_and_inputs_for_common()

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

                _UpperCAmelCase      :     Any        =   ["pixel_values"]
                self.assertListEqual(arg_names[:1]					,     A						)



      def 						snake_case_ (					self					:     List[str]						):
           _UpperCAmelCase      :     Dict        =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*A						)



      def 						snake_case_ (					self					:     Dict						):
           _UpperCAmelCase      :     Optional[Any]        =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_depth_estimation(*A						)



      def 						snake_case_ (					self					:     Dict						):
           _UpperCAmelCase      :     Tuple        =   self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*A						)



      def 						snake_case_ (					self					:     Optional[int]						):
           for model_class in self.all_model_classes:
                if model_class.__name__ == "DPTForDepthEstimation":
                     continue

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

                if model_class in get_values(A						):
                     continue

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



      def 						snake_case_ (					self					:     Dict						):
           for model_class in self.all_model_classes:
                if model_class.__name__ == "DPTForDepthEstimation":
                     continue

                _UpperCAmelCase    ,	_UpperCAmelCase      :     List[Any]        =   self.model_tester.prepare_config_and_inputs_for_common()
                _UpperCAmelCase      :     Tuple        =   False
                _UpperCAmelCase      :     Tuple        =   True

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



      def 						snake_case_ (					self					:     Union[str, Any]						):
           _UpperCAmelCase    ,	_UpperCAmelCase      :     Tuple        =   self.model_tester.prepare_config_and_inputs_for_common()

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



      @slow
      def 						snake_case_ (					self					:     Dict						):
           for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
                _UpperCAmelCase      :     Any        =   DPTModel.from_pretrained(A						)
                self.assertIsNotNone(A						)



      def 						snake_case_ (					self					:     Tuple						):
           # We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
           _UpperCAmelCase    ,	_UpperCAmelCase      :     List[str]        =   self.model_tester.prepare_config_and_inputs_for_common()
           _UpperCAmelCase      :     Optional[Any]        =   "add"
           with self.assertRaises(A						):
                _UpperCAmelCase      :     List[Any]        =   DPTForDepthEstimation(A						)







def 						__snake_case						(				)  ->       Optional[int]:





     '''simple docstring'''

     _UpperCAmelCase      :     int        =   Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
     return image






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



      def 						snake_case_ (					self					:     List[str]						):
           _UpperCAmelCase      :     Optional[int]        =   DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas"						)
           _UpperCAmelCase      :     Any        =   DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas"						).to(A						)

           _UpperCAmelCase      :     str        =   prepare_img()
           _UpperCAmelCase      :     Tuple        =   image_processor(images=A					,     return_tensors="pt"						).to(A						)

           # forward pass
           with torch.no_grad():
                _UpperCAmelCase      :     int        =   model(**A						)
                _UpperCAmelCase      :     List[str]        =   outputs.predicted_depth

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

           _UpperCAmelCase      :     int        =   torch.tensor(
               [[[5.6_437, 5.6_146, 5.6_511], [5.4_371, 5.5_649, 5.5_958], [5.5_215, 5.5_184, 5.5_293]]]						).to(A						)

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