





'''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 					__snake_case  :






   '''simple docstring'''





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

   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Tuple    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

    snake_case__     :					Union[str, Any]    =  self.get_config()

    return config, pixel_values, labels

   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Any    =  {
        """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=__SCREAMING_SNAKE_CASE	,		initializer_range=self.initializer_range	,		is_hybrid=self.is_hybrid	,		backbone_config=__SCREAMING_SNAKE_CASE	,		backbone_featmap_shape=self.backbone_featmap_shape	,		)

   def 		__UpperCamelCase						(							self	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       ):
    snake_case__     :					Dict    =  DPTModel(config=__SCREAMING_SNAKE_CASE       )
    model.to(__SCREAMING_SNAKE_CASE       )
    model.eval()
    snake_case__     :					Union[str, Any]    =  model(__SCREAMING_SNAKE_CASE       )
    self.parent.assertEqual(result.last_hidden_state.shape	,		(self.batch_size, self.seq_length, self.hidden_size)       )

   def 		__UpperCamelCase						(							self	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       ):
    snake_case__     :					Optional[Any]    =  self.num_labels
    snake_case__     :					str    =  DPTForDepthEstimation(__SCREAMING_SNAKE_CASE       )
    model.to(__SCREAMING_SNAKE_CASE       )
    model.eval()
    snake_case__     :					Optional[Any]    =  model(__SCREAMING_SNAKE_CASE       )
    self.parent.assertEqual(result.predicted_depth.shape	,		(self.batch_size, self.image_size, self.image_size)       )

   def 		__UpperCamelCase						(							self	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE       ):
    snake_case__     :					Any    =  self.num_labels
    snake_case__     :					Dict    =  DPTForSemanticSegmentation(__SCREAMING_SNAKE_CASE       )
    model.to(__SCREAMING_SNAKE_CASE       )
    model.eval()
    snake_case__     :					str    =  model(__SCREAMING_SNAKE_CASE	,		labels=__SCREAMING_SNAKE_CASE       )
    self.parent.assertEqual(
        result.logits.shape	,		(self.batch_size, self.num_labels, self.image_size, self.image_size)       )


   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Union[str, Any]    =  self.prepare_config_and_inputs()
    snake_case__  ,							snake_case__  ,							snake_case__     :					Any    =  config_and_inputs
    snake_case__     :					Optional[int]    =  {"""pixel_values""": pixel_values}
    return config, inputs_dict



@require_torch
class 					__snake_case  (					__SCREAMING_SNAKE_CASE		,				__SCREAMING_SNAKE_CASE		,				unittest.TestCase							):






   '''simple docstring'''





   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 		__UpperCamelCase						(							self       ):
    snake_case__     :					List[Any]    =  DPTModelTester(self       )
    snake_case__     :					Any    =  ConfigTester(self	,		config_class=__SCREAMING_SNAKE_CASE	,		has_text_modality=__SCREAMING_SNAKE_CASE	,		hidden_size=3_7       )

   def 		__UpperCamelCase						(							self       ):
    self.config_tester.run_common_tests()

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

   def 		__UpperCamelCase						(							self       ):
    snake_case__  ,							snake_case__     :					Tuple    =  self.model_tester.prepare_config_and_inputs_for_common()

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

   def 		__UpperCamelCase						(							self       ):
    snake_case__  ,							snake_case__     :					Dict    =  self.model_tester.prepare_config_and_inputs_for_common()

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

     snake_case__     :					str    =  ["""pixel_values"""]
     self.assertListEqual(arg_names[:1]	,		__SCREAMING_SNAKE_CASE       )

   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					List[Any]    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE       )

   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Dict    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_depth_estimation(*__SCREAMING_SNAKE_CASE       )

   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					str    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_semantic_segmentation(*__SCREAMING_SNAKE_CASE       )

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

     snake_case__  ,							snake_case__     :					str    =  self.model_tester.prepare_config_and_inputs_for_common()
     snake_case__     :					int    =  True

     if model_class in get_values(__SCREAMING_SNAKE_CASE       ):
      continue

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

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

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

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

   def 		__UpperCamelCase						(							self       ):
    snake_case__  ,							snake_case__     :					str    =  self.model_tester.prepare_config_and_inputs_for_common()

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

   @slow
   def 		__UpperCamelCase						(							self       ):
    for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
     snake_case__     :					List[str]    =  DPTModel.from_pretrained(__SCREAMING_SNAKE_CASE       )
     self.assertIsNotNone(__SCREAMING_SNAKE_CASE       )


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



def        UpperCamelCase__		(						)				->			Dict:
 '''simple docstring'''






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





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






   '''simple docstring'''





   def 		__UpperCamelCase						(							self       ):
    snake_case__     :					Dict    =  DPTImageProcessor.from_pretrained("""Intel/dpt-hybrid-midas"""       )
    snake_case__     :					Union[str, Any]    =  DPTForDepthEstimation.from_pretrained("""Intel/dpt-hybrid-midas"""       ).to(__SCREAMING_SNAKE_CASE       )

    snake_case__     :					Optional[Any]    =  prepare_img()
    snake_case__     :					Optional[int]    =  image_processor(images=__SCREAMING_SNAKE_CASE	,		return_tensors="""pt"""       ).to(__SCREAMING_SNAKE_CASE       )

    # forward pass
    with torch.no_grad():
     snake_case__     :					Dict    =  model(**__SCREAMING_SNAKE_CASE       )
     snake_case__     :					Tuple    =  outputs.predicted_depth

    # verify the predicted depth
    snake_case__     :					Any    =  torch.Size((1, 3_8_4, 3_8_4)       )
    self.assertEqual(predicted_depth.shape	,		__SCREAMING_SNAKE_CASE       )

    snake_case__     :					List[Any]    =  torch.tensor(
        [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]]       ).to(__SCREAMING_SNAKE_CASE       )

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











'''simple docstring'''

from __future__ import annotations







def    a__							(							lowercase   :	list,   lowercase   :	int )						->						List[Any]:





     """simple docstring"""

     if len(lowercase ) <= 1 or n <= 1:
          return

     insert_next(lowercase,   n - 1 )
     rec_insertion_sort(lowercase,   n - 1 )







def    a__							(							lowercase   :	list,   lowercase   :	int )						->						Optional[Any]:





     """simple docstring"""

     if index >= len(lowercase ) or collection[index - 1] <= collection[index]:
          return

     # Swaps adjacent elements since they are not in ascending order
     _UpperCamelCase       ,							_UpperCamelCase							       =			(
         collection[index],
         collection[index - 1],
     )

     insert_next(lowercase,   index + 1 )


if __name__ == "__main__":
   lowercase__		:     str			=							input('Enter integers separated by spaces: ')
   lowercase__		:     list[int]			=							[int(num) for num in numbers.split()]
   rec_insertion_sort(number_list, len(number_list))
   print(number_list)



