
"""simple docstring"""





import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ConvNextConfig, UperNetConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import is_torch_available, is_vision_available

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 transformers import UperNetForSemanticSegmentation
  from transformers.models.upernet.modeling_upernet import UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor



class __lowerCAmelCase				:




   """simple docstring"""







   def __init__(				self						:					Dict       ,   _snake_case						:					Optional[int]       ,   _snake_case						:					Any=13       ,   _snake_case						:					int=32       ,   _snake_case						:					List[Any]=3       ,   _snake_case						:					str=4       ,   _snake_case						:					Optional[int]=[10, 20, 30, 40]       ,   _snake_case						:					Optional[Any]=[2, 2, 3, 2]       ,   _snake_case						:					List[Any]=True       ,   _snake_case						:					Dict=True       ,   _snake_case						:					Tuple=37       ,   _snake_case						:					str="gelu"       ,   _snake_case						:					List[Any]=10       ,   _snake_case						:					Dict=0.0_2       ,   _snake_case						:					int=["stage2", "stage3", "stage4"]       ,   _snake_case						:					Union[str, Any]=3       ,   _snake_case						:					List[str]=None       ,   )      -> Optional[int]:







        """simple docstring"""
        A_				 =						parent
        A_				 =						batch_size
        A_				 =						image_size
        A_				 =						num_channels
        A_				 =						num_stages
        A_				 =						hidden_sizes
        A_				 =						depths
        A_				 =						is_training
        A_				 =						use_labels
        A_				 =						intermediate_size
        A_				 =						hidden_act
        A_				 =						type_sequence_label_size
        A_				 =						initializer_range
        A_				 =						out_features
        A_				 =						num_labels
        A_				 =						scope
        A_				 =						num_stages




   def      lowerCamelCase__     (				self						:					int	)      -> str:







        """simple docstring"""
        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.type_sequence_label_size	)

        A_				 =						self.get_config()

        return config, pixel_values, labels




   def      lowerCamelCase__     (				self						:					int	)      -> str:







        """simple docstring"""
        return ConvNextConfig(
            num_channels=self.num_channels       ,   num_stages=self.num_stages       ,   hidden_sizes=self.hidden_sizes       ,   depths=self.depths       ,   is_training=self.is_training       ,   intermediate_size=self.intermediate_size       ,   hidden_act=self.hidden_act       ,   out_features=self.out_features       ,   )




   def      lowerCamelCase__     (				self						:					List[str]	)      -> Union[str, Any]:







        """simple docstring"""
        return UperNetConfig(
            backbone_config=self.get_backbone_config()       ,   hidden_size=512       ,   pool_scales=[1, 2, 3, 6]       ,   use_auxiliary_head=UpperCamelCase_       ,   auxiliary_loss_weight=0.4       ,   auxiliary_in_channels=40       ,   auxiliary_channels=256       ,   auxiliary_num_convs=1       ,   auxiliary_concat_input=UpperCamelCase_       ,   loss_ignore_index=255       ,   num_labels=self.num_labels       ,   )




   def      lowerCamelCase__     (				self						:					Dict       ,   _snake_case						:					Union[str, Any]       ,   _snake_case						:					Union[str, Any]       ,   _snake_case						:					List[str]	)      -> List[str]:







        """simple docstring"""
        A_				 =						UperNetForSemanticSegmentation(config=UpperCamelCase_	)
        model.to(UpperCamelCase_	)
        model.eval()
        A_				 =						model(UpperCamelCase_	)
        self.parent.assertEqual(
            result.logits.shape       ,   (self.batch_size, self.num_labels, self.image_size, self.image_size)	)






   def      lowerCamelCase__     (				self						:					Union[str, Any]	)      -> int:







        """simple docstring"""
        A_				 =						self.prepare_config_and_inputs()
        (
            A_    
        )				 =						config_and_inputs
        A_				 =						{'pixel_values': pixel_values}
        return config, inputs_dict





@require_torch
class __lowerCAmelCase				(					_lowercase     ,				_lowercase     ,				unittest.TestCase      ):




   """simple docstring"""







   snake_case	      =				(UperNetForSemanticSegmentation,) if is_torch_available() else ()
   snake_case	      =				{"image-segmentation": UperNetForSemanticSegmentation} if is_torch_available() else {}
   snake_case	      =				False
   snake_case	      =				False
   snake_case	      =				False
   snake_case	      =				False
   snake_case	      =				False
   snake_case	      =				False




   def      lowerCamelCase__     (				self						:					str	)      -> Any:







        """simple docstring"""
        A_				 =						UperNetModelTester(self	)
        A_				 =						ConfigTester(self       ,   config_class=UpperCamelCase_       ,   has_text_modality=UpperCamelCase_       ,   hidden_size=37	)




   def      lowerCamelCase__     (				self						:					Tuple	)      -> Optional[int]:







        """simple docstring"""
        self.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()




   def      lowerCamelCase__     (				self						:					Tuple	)      -> Any:







        """simple docstring"""
        return




   def      lowerCamelCase__     (				self						:					List[str]	)      -> Any:







        """simple docstring"""
        A_				 =						self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             A_				 =						model_class(UpperCamelCase_	)
             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]       ,   UpperCamelCase_	)




   def      lowerCamelCase__     (				self						:					Dict	)      -> Dict:







        """simple docstring"""
        A_				 =						self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase_	)




   @unittest.skip(reason="UperNet does not use inputs_embeds"	)
   def      lowerCamelCase__     (				self						:					List[Any]	)      -> int:







        """simple docstring"""
        pass




   @unittest.skip(reason="UperNet does not support input and output embeddings"	)
   def      lowerCamelCase__     (				self						:					List[str]	)      -> Tuple:







        """simple docstring"""
        pass




   @unittest.skip(reason="UperNet does not have a base model"	)
   def      lowerCamelCase__     (				self						:					Union[str, Any]	)      -> int:







        """simple docstring"""
        pass




   @unittest.skip(reason="UperNet does not have a base model"	)
   def      lowerCamelCase__     (				self						:					Optional[Any]	)      -> Dict:







        """simple docstring"""
        pass




   @require_torch_multi_gpu
   @unittest.skip(reason="UperNet has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`"	)
   def      lowerCamelCase__     (				self						:					Any	)      -> Union[str, Any]:







        """simple docstring"""
        pass




   @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."	)
   def      lowerCamelCase__     (				self						:					Union[str, Any]	)      -> List[str]:







        """simple docstring"""
        pass




   def      lowerCamelCase__     (				self						:					List[Any]	)      -> Optional[Any]:







        """simple docstring"""





        def check_hidden_states_output(_snake_case						:					List[str]       ,   _snake_case						:					str       ,   _snake_case						:					Dict	):
             A_				 =						model_class(UpperCamelCase_	)
             model.to(UpperCamelCase_	)
             model.eval()

             with torch.no_grad():
                  A_				 =						model(**self._prepare_for_class(UpperCamelCase_       ,   UpperCamelCase_	)	)

             A_				 =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             A_				 =						self.model_tester.num_stages
             self.assertEqual(len(UpperCamelCase_	)       ,   expected_num_stages + 1	)

             # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
             self.assertListEqual(
                 list(hidden_states[0].shape[-2:]	)       ,   [self.model_tester.image_size // 4, self.model_tester.image_size // 4]       ,   )

        A_				 =						self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             A_				 =						True
             check_hidden_states_output(UpperCamelCase_       ,   UpperCamelCase_       ,   UpperCamelCase_	)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             A_				 =						True

             check_hidden_states_output(UpperCamelCase_       ,   UpperCamelCase_       ,   UpperCamelCase_	)




   def      lowerCamelCase__     (				self						:					List[str]	)      -> List[Any]:







        """simple docstring"""
        A_				 =						self.model_tester.prepare_config_and_inputs_for_common()

        A_				 =						_config_zero_init(UpperCamelCase_	)
        A_				 =						_config_zero_init(configs_no_init.backbone_config	)
        for model_class in self.all_model_classes:
             A_				 =						model_class(config=UpperCamelCase_	)
             for name, param in model.named_parameters():
                  if param.requires_grad:
                       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(reason="UperNet does not have tied weights"	)
   def      lowerCamelCase__     (				self						:					Optional[Any]	)      -> List[Any]:







        """simple docstring"""
        pass






   @slow
   def      lowerCamelCase__     (				self						:					List[str]	)      -> List[str]:







        """simple docstring"""





        for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             A_				 =						UperNetForSemanticSegmentation.from_pretrained(UpperCamelCase_	)
             self.assertIsNotNone(UpperCamelCase_	)





def 							A_     ():

     '''simple docstring'''





     A_				 =						hf_hub_download(
         repo_id="hf-internal-testing/fixtures_ade20k"				,   repo_type="dataset"				,   filename="ADE_val_00000001.jpg"				)
     A_				 =						Image.open(_lowercase				).convert("RGB"				)
     return image




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




   """simple docstring"""







   def      lowerCamelCase__     (				self						:					Optional[Any]	)      -> List[str]:







        """simple docstring"""
        A_				 =						AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny"	)
        A_				 =						UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny"	).to(UpperCamelCase_	)

        A_				 =						prepare_img()
        A_				 =						processor(images=UpperCamelCase_       ,   return_tensors="pt"	).to(UpperCamelCase_	)

        with torch.no_grad():
             A_				 =						model(**UpperCamelCase_	)

        A_				 =						torch.Size((1, model.config.num_labels, 512, 512)	)
        self.assertEqual(outputs.logits.shape       ,   UpperCamelCase_	)

        A_				 =						torch.tensor(
            [[-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.5_9_5_8, -7.5_9_5_8, -7.4_3_0_2], [-7.4_7_9_7, -7.4_7_9_7, -7.3_0_6_8]]	).to(UpperCamelCase_	)
        self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]       ,   UpperCamelCase_       ,   atol=1e-4	)	)






   def      lowerCamelCase__     (				self						:					str	)      -> int:







        """simple docstring"""
        A_				 =						AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny"	)
        A_				 =						UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny"	).to(UpperCamelCase_	)

        A_				 =						prepare_img()
        A_				 =						processor(images=UpperCamelCase_       ,   return_tensors="pt"	).to(UpperCamelCase_	)

        with torch.no_grad():
             A_				 =						model(**UpperCamelCase_	)

        A_				 =						torch.Size((1, model.config.num_labels, 512, 512)	)
        self.assertEqual(outputs.logits.shape       ,   UpperCamelCase_	)

        A_				 =						torch.tensor(
            [[-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.8_1_1_0, -8.8_1_1_0, -8.6_5_2_1], [-8.7_7_4_6, -8.7_7_4_6, -8.6_1_3_0]]	).to(UpperCamelCase_	)
        self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]       ,   UpperCamelCase_       ,   atol=1e-4	)	)






"""simple docstring"""





from __future__ import annotations

import math

UpperCamelCase_					:						List[str]				= '''2020.9.26'''
UpperCamelCase_					:						List[Any]				= '''xcodz-dot, cclaus, dhruvmanila'''
def 							A_     (__a				,   __a				,   __a				,   __a				,   __a				):

					'''simple docstring'''





					if not all(isinstance(__a				,   (float, int)				) for val in locals().values()				):
										A_				 =						f'Input values must either be float or int: {list(locals().values()				)}'
										raise TypeError(__a				)
					A_				 =						((x * distance) / (z + distance)) * scale
					A_				 =						((y * distance) / (z + distance)) * scale
					return projected_x, projected_y
def 							A_     (__a				,   __a				,   __a				,   __a				,   __a				):

					'''simple docstring'''





					if not isinstance(__a				,   __a				):
										raise TypeError("Axis must be a str"				)
					A_				 =						locals()
					del input_variables["axis"]
					if not all(isinstance(__a				,   (float, int)				) for val in input_variables.values()				):
										A_				 =						(
										    "Input values except axis must either be float or int: "
										    f'{list(input_variables.values()				)}'
										)
										raise TypeError(__a				)
					A_				 =						(angle % 360) / 450 * 180 / math.pi
					if axis == "z":
										A_				 =						x * math.cos(__a				) - y * math.sin(__a				)
										A_				 =						y * math.cos(__a				) + x * math.sin(__a				)
										A_				 =						z
					elif axis == "x":
										A_				 =						y * math.cos(__a				) - z * math.sin(__a				)
										A_				 =						z * math.cos(__a				) + y * math.sin(__a				)
										A_				 =						x
					elif axis == "y":
										A_				 =						x * math.cos(__a				) - z * math.sin(__a				)
										A_				 =						z * math.cos(__a				) + x * math.sin(__a				)
										A_				 =						y
					else:
										raise ValueError("not a valid axis, choose one of 'x', 'y', 'z'"				)

					return new_x, new_y, new_z


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		print(F"""{convert_to_ad(1.0, 2.0, 3.0, 10.0, 10.0) = }""")
		print(F"""{rotate(1.0, 2.0, 3.0, 'y', 90.0) = }""")




