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



  def __init__(		self   :    int						,  lowerCamelCase_   :    Any						,  lowerCamelCase_   :    Optional[Any]=2						,  lowerCamelCase_   :    List[Any]=32						,  lowerCamelCase_   :    str=16						,  lowerCamelCase_   :    Union[str, Any]=3						,  lowerCamelCase_   :    Dict=True						,  lowerCamelCase_   :    Dict=True						,  lowerCamelCase_   :    int=32						,  lowerCamelCase_   :    int=4						,  lowerCamelCase_   :    int=[0, 1, 2, 3]						,  lowerCamelCase_   :    Union[str, Any]=4						,  lowerCamelCase_   :    List[Any]=37						,  lowerCamelCase_   :    Any="gelu"						,  lowerCamelCase_   :    List[Any]=0.1						,  lowerCamelCase_   :    Union[str, Any]=0.1						,  lowerCamelCase_   :    Dict=0.02						,  lowerCamelCase_   :    Dict=3						,  lowerCamelCase_   :    List[str]=False						,  lowerCamelCase_   :    Tuple=None						,  )      -> List[str]:
      __a			      =						parent
      __a			      =						batch_size
      __a			      =						image_size
      __a			      =						patch_size
      __a			      =						num_channels
      __a			      =						is_training
      __a			      =						use_labels
      __a			      =						hidden_size
      __a			      =						num_hidden_layers
      __a			      =						backbone_out_indices
      __a			      =						num_attention_heads
      __a			      =						intermediate_size
      __a			      =						hidden_act
      __a			      =						hidden_dropout_prob
      __a			      =						attention_probs_dropout_prob
      __a			      =						initializer_range
      __a			      =						num_labels
      __a			      =						scope
      __a			      =						is_hybrid
      # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
      __a			      =						(image_size // patch_size) ** 2
      __a			      =						num_patches + 1



  def        lowerCAmelCase_				(		self   :    Dict     )      -> Union[str, Any]:
      __a			      =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

      __a			      =						self.get_config()

      return config, pixel_values, labels



  def        lowerCAmelCase_				(		self   :    Union[str, Any]     )      -> int:
      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=lowerCamelCase_						,  initializer_range=self.initializer_range						,  is_hybrid=self.is_hybrid						,  )



  def        lowerCAmelCase_				(		self   :    List[str]						,  lowerCamelCase_   :    List[Any]						,  lowerCamelCase_   :    Dict						,  lowerCamelCase_   :    Any     )      -> Union[str, Any]:
      __a			      =						DPTModel(config=lowerCamelCase_     )
      model.to(lowerCamelCase_     )
      model.eval()
      __a			      =						model(lowerCamelCase_     )
      self.parent.assertEqual(result.last_hidden_state.shape						,  (self.batch_size, self.seq_length, self.hidden_size)     )



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



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



  def        lowerCAmelCase_				(		self   :    Tuple     )      -> Optional[int]:
      __a			      =						self.prepare_config_and_inputs()
      __a      ,  __a      ,  __a			      =						config_and_inputs
      __a			      =						{"""pixel_values""": pixel_values}
      return config, inputs_dict






@require_torch
class 					a					(				A_   ,		A_   ,		unittest.TestCase							):
  A_ :				int 			=							(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
  A_ :				List[Any] 			=							(
      {
          '''depth-estimation''': DPTForDepthEstimation,
          '''feature-extraction''': DPTModel,
          '''image-segmentation''': DPTForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  A_ :				Tuple 			=							False
  A_ :				List[str] 			=							False
  A_ :				Tuple 			=							False



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



  def        lowerCAmelCase_				(		self   :    Any     )      -> Optional[Any]:
      self.config_tester.run_common_tests()



  @unittest.skip(reason="""DPT does not use inputs_embeds"""     )
  def        lowerCAmelCase_				(		self   :    str     )      -> Optional[int]:
      pass



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

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



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

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

          __a			      =						["""pixel_values"""]
          self.assertListEqual(arg_names[:1]						,  lowerCamelCase_     )



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



  def        lowerCAmelCase_				(		self   :    Optional[Any]     )      -> List[Any]:
      __a			      =						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_depth_estimation(*lowerCamelCase_     )



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



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

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

          if model_class in get_values(lowerCamelCase_     ):
              continue

          __a			      =						model_class(lowerCamelCase_     )
          model.to(lowerCamelCase_     )
          model.train()
          __a			      =						self._prepare_for_class(lowerCamelCase_						,  lowerCamelCase_						,  return_labels=lowerCamelCase_     )
          __a			      =						model(**lowerCamelCase_     ).loss
          loss.backward()



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

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

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



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

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



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

def 						UpperCamelCase				(	):
    __a			      =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
    return image






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



  def        lowerCAmelCase_				(		self   :    List[Any]     )      -> Tuple:
      __a			      =						DPTImageProcessor.from_pretrained("""Intel/dpt-large"""     )
      __a			      =						DPTForDepthEstimation.from_pretrained("""Intel/dpt-large"""     ).to(lowerCamelCase_     )

      __a			      =						prepare_img()
      __a			      =						image_processor(images=lowerCamelCase_						,  return_tensors="""pt"""     ).to(lowerCamelCase_     )

      # forward pass
      with torch.no_grad():
          __a			      =						model(**lowerCamelCase_     )
          __a			      =						outputs.predicted_depth

      # verify the predicted depth
      __a			      =						torch.Size((1, 3_84, 3_84)     )
      self.assertEqual(predicted_depth.shape						,  lowerCamelCase_     )

      __a			      =						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(lowerCamelCase_     )

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



  def        lowerCAmelCase_				(		self   :    Union[str, Any]     )      -> str:
      __a			      =						DPTImageProcessor.from_pretrained("""Intel/dpt-large-ade"""     )
      __a			      =						DPTForSemanticSegmentation.from_pretrained("""Intel/dpt-large-ade"""     ).to(lowerCamelCase_     )

      __a			      =						prepare_img()
      __a			      =						image_processor(images=lowerCamelCase_						,  return_tensors="""pt"""     ).to(lowerCamelCase_     )

      # forward pass
      with torch.no_grad():
          __a			      =						model(**lowerCamelCase_     )

      # verify the logits
      __a			      =						torch.Size((1, 1_50, 4_80, 4_80)     )
      self.assertEqual(outputs.logits.shape						,  lowerCamelCase_     )

      __a			      =						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(lowerCamelCase_     )

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



  def        lowerCAmelCase_				(		self   :    str     )      -> str:
      __a			      =						DPTImageProcessor.from_pretrained("""Intel/dpt-large-ade"""     )
      __a			      =						DPTForSemanticSegmentation.from_pretrained("""Intel/dpt-large-ade"""     ).to(lowerCamelCase_     )

      __a			      =						prepare_img()
      __a			      =						image_processor(images=lowerCamelCase_						,  return_tensors="""pt"""     ).to(lowerCamelCase_     )

      # forward pass
      with torch.no_grad():
          __a			      =						model(**lowerCamelCase_     )

      __a			      =						outputs.logits.detach().cpu()

      __a			      =						image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase_						,  target_sizes=[(5_00, 3_00)]     )
      __a			      =						torch.Size((5_00, 3_00)     )
      self.assertEqual(segmentation[0].shape						,  lowerCamelCase_     )

      __a			      =						image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase_     )
      __a			      =						torch.Size((4_80, 4_80)     )
      self.assertEqual(segmentation[0].shape						,  lowerCamelCase_     )

"""simple docstring"""


from doctest import testmod
from math import sqrt

def 						UpperCamelCase				(	_lowerCAmelCase   :							int						):
    __a			      =						[]
    if num < 1:
        return facs
    facs.append(1						)
    if num == 1:
        return facs
    facs.append(_lowerCAmelCase						)
    for i in range(2				, int(sqrt(_lowerCAmelCase						)						) + 1						):
        if num % i == 0:  # If i is a factor of num
            facs.append(_lowerCAmelCase						)
            __a			      =						num // i  # num//i is the other factor of num
            if d != i:  # If d and i are distinct
                facs.append(_lowerCAmelCase						)  # we have found another factor
    facs.sort()
    return facs


if __name__ == "__main__":
 testmod(name="""factors_of_a_number""", verbose=True)
