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




				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.02							,							_UpperCamelCase=3							,							_UpperCamelCase=[1, 384, 24, 24]							,							_UpperCamelCase=True							,							_UpperCamelCase=None							,							)							-> List[Any]:
							lowerCAmelCase_         =      parent
							lowerCAmelCase_         =      batch_size
							lowerCAmelCase_         =      image_size
							lowerCAmelCase_         =      patch_size
							lowerCAmelCase_         =      num_channels
							lowerCAmelCase_         =      is_training
							lowerCAmelCase_         =      use_labels
							lowerCAmelCase_         =      hidden_size
							lowerCAmelCase_         =      num_hidden_layers
							lowerCAmelCase_         =      backbone_out_indices
							lowerCAmelCase_         =      num_attention_heads
							lowerCAmelCase_         =      intermediate_size
							lowerCAmelCase_         =      hidden_act
							lowerCAmelCase_         =      hidden_dropout_prob
							lowerCAmelCase_         =      attention_probs_dropout_prob
							lowerCAmelCase_         =      initializer_range
							lowerCAmelCase_         =      num_labels
							lowerCAmelCase_         =      backbone_featmap_shape
							lowerCAmelCase_         =      scope
							lowerCAmelCase_         =      is_hybrid
							# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
							lowerCAmelCase_         =      (image_size // patch_size) ** 2
							lowerCAmelCase_         =      num_patches + 1




				def 	__a		(   self	)							-> Tuple:
							lowerCAmelCase_         =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

							lowerCAmelCase_         =      self.get_config()

							return config, pixel_values, labels




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




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)							-> Optional[int]:
							lowerCAmelCase_         =      DPTModel(config=_UpperCamelCase	)
							model.to(_UpperCamelCase	)
							model.eval()
							lowerCAmelCase_         =      model(_UpperCamelCase	)
							self.parent.assertEqual(result.last_hidden_state.shape							,							(self.batch_size, self.seq_length, self.hidden_size)	)




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)							-> List[Any]:
							lowerCAmelCase_         =      self.num_labels
							lowerCAmelCase_         =      DPTForDepthEstimation(_UpperCamelCase	)
							model.to(_UpperCamelCase	)
							model.eval()
							lowerCAmelCase_         =      model(_UpperCamelCase	)
							self.parent.assertEqual(result.predicted_depth.shape							,							(self.batch_size, self.image_size, self.image_size)	)




				def 	__a		(   self							,							_UpperCamelCase							,							_UpperCamelCase							,							_UpperCamelCase	)							-> Union[str, Any]:
							lowerCAmelCase_         =      self.num_labels
							lowerCAmelCase_         =      DPTForSemanticSegmentation(_UpperCamelCase	)
							model.to(_UpperCamelCase	)
							model.eval()
							lowerCAmelCase_         =      model(_UpperCamelCase							,							labels=_UpperCamelCase	)
							self.parent.assertEqual(
							    result.logits.shape							,							(self.batch_size, self.num_labels, self.image_size, self.image_size)	)




				def 	__a		(   self	)							-> Any:
							lowerCAmelCase_         =      self.prepare_config_and_inputs()
							lowerCAmelCase_      ,    lowerCAmelCase_      ,    lowerCAmelCase_         =      config_and_inputs
							lowerCAmelCase_         =      {"pixel_values": pixel_values}
							return config, inputs_dict





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

				_lowercase     						=False
				_lowercase     						=False
				_lowercase     						=False




				def 	__a		(   self	)							-> List[str]:
							lowerCAmelCase_         =      DPTModelTester(self	)
							lowerCAmelCase_         =      ConfigTester(self							,							config_class=_UpperCamelCase							,							has_text_modality=_UpperCamelCase							,							hidden_size=37	)




				def 	__a		(   self	)							-> str:
							self.config_tester.run_common_tests()




				@unittest.skip(reason="DPT does not use inputs_embeds"	)
				def 	__a		(   self	)							-> Tuple:
							pass




				def 	__a		(   self	)							-> Tuple:
							lowerCAmelCase_      ,    lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs_for_common()

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




				def 	__a		(   self	)							-> Any:
							lowerCAmelCase_      ,    lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs_for_common()

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

										lowerCAmelCase_         =      ["pixel_values"]
										self.assertListEqual(arg_names[:1]							,							_UpperCamelCase	)




				def 	__a		(   self	)							-> Tuple:
							lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_UpperCamelCase	)




				def 	__a		(   self	)							-> Dict:
							lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_depth_estimation(*_UpperCamelCase	)




				def 	__a		(   self	)							-> Union[str, Any]:
							lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCamelCase	)




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

										lowerCAmelCase_      ,    lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs_for_common()
										lowerCAmelCase_         =      True

										if model_class in get_values(_UpperCamelCase	):
													continue

										lowerCAmelCase_         =      model_class(_UpperCamelCase	)
										model.to(_UpperCamelCase	)
										model.train()
										lowerCAmelCase_         =      self._prepare_for_class(_UpperCamelCase							,							_UpperCamelCase							,							return_labels=_UpperCamelCase	)
										lowerCAmelCase_         =      model(**_UpperCamelCase	).loss
										loss.backward()




				def 	__a		(   self	)							-> int:
							for model_class in self.all_model_classes:
										if model_class.__name__ == "DPTForDepthEstimation":
													continue

										lowerCAmelCase_      ,    lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs_for_common()
										lowerCAmelCase_         =      False
										lowerCAmelCase_         =      True

										if model_class in get_values(_UpperCamelCase	) or not model_class.supports_gradient_checkpointing:
													continue
										lowerCAmelCase_         =      model_class(_UpperCamelCase	)
										model.to(_UpperCamelCase	)
										model.gradient_checkpointing_enable()
										model.train()
										lowerCAmelCase_         =      self._prepare_for_class(_UpperCamelCase							,							_UpperCamelCase							,							return_labels=_UpperCamelCase	)
										lowerCAmelCase_         =      model(**_UpperCamelCase	).loss
										loss.backward()




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

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




				@slow
				def 	__a		(   self	)							-> Optional[int]:
							for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
										lowerCAmelCase_         =      DPTModel.from_pretrained(_UpperCamelCase	)
										self.assertIsNotNone(_UpperCamelCase	)




				def 	__a		(   self	)							-> Optional[Any]:
							# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
							lowerCAmelCase_      ,    lowerCAmelCase_         =      self.model_tester.prepare_config_and_inputs_for_common()
							lowerCAmelCase_         =      "add"
							with self.assertRaises(_UpperCamelCase	):
										lowerCAmelCase_         =      DPTForDepthEstimation(_UpperCamelCase	)






def   lowerCamelCase__							(							):




			"""simple docstring"""


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





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




				def 	__a		(   self	)							-> int:
							lowerCAmelCase_         =      DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas"	)
							lowerCAmelCase_         =      DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas"	).to(_UpperCamelCase	)

							lowerCAmelCase_         =      prepare_img()
							lowerCAmelCase_         =      image_processor(images=_UpperCamelCase							,							return_tensors="pt"	).to(_UpperCamelCase	)

							# forward pass
							with torch.no_grad():
										lowerCAmelCase_         =      model(**_UpperCamelCase	)
										lowerCAmelCase_         =      outputs.predicted_depth

							# verify the predicted depth
							lowerCAmelCase_         =      torch.Size((1, 384, 384)	)
							self.assertEqual(predicted_depth.shape							,							_UpperCamelCase	)

							lowerCAmelCase_         =      torch.tensor(
							    [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]]	).to(_UpperCamelCase	)

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





from math import sqrt






def   lowerCamelCase__							(							__lowerCAmelCase    :    int							):




			"""simple docstring"""


			lowerCAmelCase_         =      0
			for i in range(1       ,				int(sqrt(__lowerCAmelCase							) + 1							)							):
						if n % i == 0 and i != sqrt(__lowerCAmelCase							):
									total += i + n // i
						elif i == sqrt(__lowerCAmelCase							):
									total += i
			return total - n






def   lowerCamelCase__							(							__lowerCAmelCase    :    int = 10000							):




			"""simple docstring"""


			lowerCAmelCase_         =      sum(
			    i
			    for i in range(1       ,				__lowerCAmelCase							)
			    if sum_of_divisors(sum_of_divisors(__lowerCAmelCase							)							) == i and sum_of_divisors(__lowerCAmelCase							) != i							)
			return total


if __name__ == "__main__":
			print(solution(int(str(input()).strip())))



