


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






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


          '''simple docstring'''


          UpperCAmelCase__     :						Tuple						=							parent
          UpperCAmelCase__     :						Dict						=							batch_size
          UpperCAmelCase__     :						int						=							image_size
          UpperCAmelCase__     :						int						=							num_channels
          UpperCAmelCase__     :						int						=							num_stages
          UpperCAmelCase__     :						List[Any]						=							hidden_sizes
          UpperCAmelCase__     :						Dict						=							depths
          UpperCAmelCase__     :						Optional[int]						=							is_training
          UpperCAmelCase__     :						Tuple						=							use_labels
          UpperCAmelCase__     :						Optional[Any]						=							intermediate_size
          UpperCAmelCase__     :						Optional[int]						=							hidden_act
          UpperCAmelCase__     :						Optional[int]						=							type_sequence_label_size
          UpperCAmelCase__     :						Optional[int]						=							initializer_range
          UpperCAmelCase__     :						Any						=							out_features
          UpperCAmelCase__     :						Optional[Any]						=							num_labels
          UpperCAmelCase__     :						Any						=							scope
          UpperCAmelCase__     :						List[str]						=							num_stages






      def lowercase_				(   self							:       Dict					):


          '''simple docstring'''


          UpperCAmelCase__     :						Optional[int]						=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

          UpperCAmelCase__     :						Any						=							None
          if self.use_labels:
              UpperCAmelCase__     :						Any						=							ids_tensor([self.batch_size]		,		self.type_sequence_label_size					)

          UpperCAmelCase__     :						List[Any]						=							self.get_config()

          return config, pixel_values, labels






      def lowercase_				(   self							:       int					):


          '''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 lowercase_				(   self							:       str					):


          '''simple docstring'''


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






      def lowercase_				(   self							:       Any		,		_A							:       int		,		_A							:       List[str]		,		_A							:       int					):


          '''simple docstring'''


          UpperCAmelCase__     :						Tuple						=							UperNetForSemanticSegmentation(config=_A					)
          model.to(_A					)
          model.eval()
          UpperCAmelCase__     :						Union[str, Any]						=							model(_A					)
          self.parent.assertEqual(
              result.logits.shape		,		(self.batch_size, self.num_labels, self.image_size, self.image_size)					)






      def lowercase_				(   self							:       str					):


          '''simple docstring'''


          UpperCAmelCase__     :						List[Any]						=							self.prepare_config_and_inputs()
          (
              (
              UpperCAmelCase__
          )		,		(
              UpperCAmelCase__
          )		,		(
              UpperCAmelCase__
          )		,		
          )     :						Optional[int]						=							config_and_inputs
          UpperCAmelCase__     :						List[Any]						=							{'''pixel_values''': pixel_values}
          return config, inputs_dict




@require_torch
class      lowerCamelCase_  (      __a	,			__a	,			unittest.TestCase ):
      lowerCAmelCase__							=	(UperNetForSemanticSegmentation,) if is_torch_available() else ()
      lowerCAmelCase__							=	{'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
      lowerCAmelCase__							=	False
      lowerCAmelCase__							=	False
      lowerCAmelCase__							=	False
      lowerCAmelCase__							=	False
      lowerCAmelCase__							=	False
      lowerCAmelCase__							=	False






      def lowercase_				(   self							:       List[Any]					):


          '''simple docstring'''


          UpperCAmelCase__     :						int						=							UperNetModelTester(self					)
          UpperCAmelCase__     :						Dict						=							ConfigTester(self		,		config_class=_A		,		has_text_modality=_A		,		hidden_size=37					)






      def lowercase_				(   self							:       Dict					):


          '''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 lowercase_				(   self							:       Dict					):


          '''simple docstring'''


          return






      def lowercase_				(   self							:       Optional[int]					):


          '''simple docstring'''


          UpperCAmelCase__		,		UpperCAmelCase__     :						Tuple						=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              UpperCAmelCase__     :						Union[str, Any]						=							model_class(_A					)
              UpperCAmelCase__     :						Tuple						=							inspect.signature(model.forward					)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              UpperCAmelCase__     :						Any						=							[*signature.parameters.keys()]

              UpperCAmelCase__     :						str						=							['''pixel_values''']
              self.assertListEqual(arg_names[:1]		,		_A					)






      def lowercase_				(   self							:       List[Any]					):


          '''simple docstring'''


          UpperCAmelCase__     :						Optional[Any]						=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*_A					)






      @unittest.skip(reason='''UperNet does not use inputs_embeds'''					)
      def lowercase_				(   self							:       int					):


          '''simple docstring'''


          pass






      @unittest.skip(reason='''UperNet does not support input and output embeddings'''					)
      def lowercase_				(   self							:       List[str]					):


          '''simple docstring'''


          pass






      @unittest.skip(reason='''UperNet does not have a base model'''					)
      def lowercase_				(   self							:       Tuple					):


          '''simple docstring'''


          pass






      @unittest.skip(reason='''UperNet does not have a base model'''					)
      def lowercase_				(   self							:       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 lowercase_				(   self							:       Optional[int]					):


          '''simple docstring'''


          pass






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


          '''simple docstring'''


          pass






      def lowercase_				(   self							:       Tuple					):


          '''simple docstring'''


          def check_hidden_states_output(_A							:       Any		,		_A							:       List[Any]		,		_A							:       Dict					):
              UpperCAmelCase__     :						str						=							model_class(_A					)
              model.to(_A					)
              model.eval()

              with torch.no_grad():
                  UpperCAmelCase__     :						Optional[Any]						=							model(**self._prepare_for_class(_A		,		_A					)					)

              UpperCAmelCase__     :						Tuple						=							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              UpperCAmelCase__     :						List[str]						=							self.model_tester.num_stages
              self.assertEqual(len(_A					)		,		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]		,		)

          UpperCAmelCase__		,		UpperCAmelCase__     :						str						=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              UpperCAmelCase__     :						Union[str, Any]						=							True
              check_hidden_states_output(_A		,		_A		,		_A					)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              UpperCAmelCase__     :						Optional[Any]						=							True

              check_hidden_states_output(_A		,		_A		,		_A					)






      def lowercase_				(   self							:       Optional[Any]					):


          '''simple docstring'''


          UpperCAmelCase__		,		UpperCAmelCase__     :						Dict						=							self.model_tester.prepare_config_and_inputs_for_common()

          UpperCAmelCase__     :						Optional[Any]						=							_config_zero_init(_A					)
          UpperCAmelCase__     :						Dict						=							_config_zero_init(configs_no_init.backbone_config					)
          for model_class in self.all_model_classes:
              UpperCAmelCase__     :						Optional[Any]						=							model_class(config=_A					)
              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 lowercase_				(   self							:       List[Any]					):


          '''simple docstring'''


          pass






      @slow
      def lowercase_				(   self							:       Optional[int]					):


          '''simple docstring'''


          for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              UpperCAmelCase__     :						Any						=							UperNetForSemanticSegmentation.from_pretrained(_A					)
              self.assertIsNotNone(_A					)





def    a__			(   )       ->      Tuple:
    UpperCAmelCase__     :						Optional[int]						=							hf_hub_download(
        repo_id='''hf-internal-testing/fixtures_ade20k'''    ,   repo_type='''dataset'''    ,   filename='''ADE_val_00000001.jpg'''		)
    UpperCAmelCase__     :						Optional[Any]						=							Image.open(lowerCAmelCase__		).convert('''RGB'''		)
    return image







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






      def lowercase_				(   self							:       Tuple					):


          '''simple docstring'''


          UpperCAmelCase__     :						Dict						=							AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny'''					)
          UpperCAmelCase__     :						Any						=							UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny'''					).to(_A					)

          UpperCAmelCase__     :						Union[str, Any]						=							prepare_img()
          UpperCAmelCase__     :						Union[str, Any]						=							processor(images=_A		,		return_tensors='''pt'''					).to(_A					)

          with torch.no_grad():
              UpperCAmelCase__     :						List[Any]						=							model(**_A					)

          UpperCAmelCase__     :						Union[str, Any]						=							torch.Size((1, model.config.num_labels, 512, 512)					)
          self.assertEqual(outputs.logits.shape		,		_A					)

          UpperCAmelCase__     :						Any						=							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(_A					)
          self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]		,		_A		,		atol=1e-4					)					)






      def lowercase_				(   self							:       List[Any]					):


          '''simple docstring'''


          UpperCAmelCase__     :						int						=							AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''					)
          UpperCAmelCase__     :						Any						=							UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''					).to(_A					)

          UpperCAmelCase__     :						str						=							prepare_img()
          UpperCAmelCase__     :						Dict						=							processor(images=_A		,		return_tensors='''pt'''					).to(_A					)

          with torch.no_grad():
              UpperCAmelCase__     :						List[str]						=							model(**_A					)

          UpperCAmelCase__     :						Tuple						=							torch.Size((1, model.config.num_labels, 512, 512)					)
          self.assertEqual(outputs.logits.shape		,		_A					)

          UpperCAmelCase__     :						List[Any]						=							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(_A					)
          self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]		,		_A		,		atol=1e-4					)					)


from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
		import PIL


lowerCamelCase__						=				logging.get_logger(__name__)







class 							lowerCAmelCase__   ( __lowercase						):
						UpperCamelCase_				:			str						=		["pixel_values"]

						def __init__(      self							,				a = True							,				a = None							,				a = PIL.Image.BICUBIC							,				a = True							,				a = None							,				a = 1 / 2_55							,				a = True							,				a = True							,				a = None							,				a = None							,				**a							,				)       ->   None:


								'''simple docstring'''

								super().__init__(**a					)
								_UpperCamelCase         =						size if size is not None else {"""height""": 2_56, """width""": 2_56}
								_UpperCamelCase         =						get_size_dict(a					)
								_UpperCamelCase         =						crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24}
								_UpperCamelCase         =						get_size_dict(a							,				param_name="""crop_size"""					)

								_UpperCamelCase         =						do_resize
								_UpperCamelCase         =						size
								_UpperCamelCase         =						resample
								_UpperCamelCase         =						do_center_crop
								_UpperCamelCase         =						crop_size
								_UpperCamelCase         =						do_rescale
								_UpperCamelCase         =						rescale_factor
								_UpperCamelCase         =						do_normalize
								_UpperCamelCase         =						image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
								_UpperCamelCase         =						image_std if image_std is not None else IMAGENET_STANDARD_STD

						def 			A_					(      self							,				a							,				a							,				a = PIL.Image.BICUBIC							,				a = None							,				**a							,				)       ->   np.ndarray:


								'''simple docstring'''

								_UpperCamelCase         =						get_size_dict(a					)
								if "height" not in size or "width" not in size:
										raise ValueError(F'The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'					)
								return resize(
								    a							,				size=(size["""height"""], size["""width"""])							,				resample=a							,				data_format=a							,				**a					)

						def 			A_					(      self							,				a							,				a							,				a = None							,				**a							,				)       ->   np.ndarray:


								'''simple docstring'''

								_UpperCamelCase         =						get_size_dict(a					)
								if "height" not in size or "width" not in size:
										raise ValueError(F'The size dictionary must have keys \'height\' and \'width\'. Got {size.keys()}'					)
								return center_crop(a							,				size=(size["""height"""], size["""width"""])							,				data_format=a							,				**a					)

						def 			A_					(      self							,				a							,				a							,				a = None							,				**a							,				)       ->   List[str]:


								'''simple docstring'''

								return rescale(a							,				scale=a							,				data_format=a							,				**a					)

						def 			A_					(      self							,				a							,				a							,				a							,				a = None							,				**a							,				)       ->   np.ndarray:


								'''simple docstring'''

								return normalize(a							,				mean=a							,				std=a							,				data_format=a							,				**a					)







						def 			A_					(      self							,				a							,				a = None							,				a = None							,				a=None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = None							,				a = ChannelDimension.FIRST							,				**a							,				)       ->   PIL.Image.Image:


								'''simple docstring'''

								_UpperCamelCase         =						do_resize if do_resize is not None else self.do_resize
								_UpperCamelCase         =						resample if resample is not None else self.resample
								_UpperCamelCase         =						do_center_crop if do_center_crop is not None else self.do_center_crop
								_UpperCamelCase         =						do_rescale if do_rescale is not None else self.do_rescale
								_UpperCamelCase         =						rescale_factor if rescale_factor is not None else self.rescale_factor
								_UpperCamelCase         =						do_normalize if do_normalize is not None else self.do_normalize
								_UpperCamelCase         =						image_mean if image_mean is not None else self.image_mean
								_UpperCamelCase         =						image_std if image_std is not None else self.image_std

								_UpperCamelCase         =						size if size is not None else self.size
								_UpperCamelCase         =						get_size_dict(a					)
								_UpperCamelCase         =						crop_size if crop_size is not None else self.crop_size
								_UpperCamelCase         =						get_size_dict(a							,				param_name="""crop_size"""					)

								_UpperCamelCase         =						make_list_of_images(a					)

								if not valid_images(a					):
										raise ValueError(
										    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
										    """torch.Tensor, tf.Tensor or jax.ndarray."""					)

								if do_resize and size is None or resample is None:
										raise ValueError("""Size and resample must be specified if do_resize is True."""					)

								if do_center_crop and crop_size is None:
										raise ValueError("""Crop size must be specified if do_center_crop is True."""					)

								if do_rescale and rescale_factor is None:
										raise ValueError("""Rescale factor must be specified if do_rescale is True."""					)

								if do_normalize and (image_mean is None or image_std is None):
										raise ValueError("""Image mean and std must be specified if do_normalize is True."""					)

								# All transformations expect numpy arrays.
								_UpperCamelCase         =						[to_numpy_array(a					) for image in images]

								if do_resize:
										_UpperCamelCase         =						[self.resize(image=a							,				size=a							,				resample=a					) for image in images]

								if do_center_crop:
										_UpperCamelCase         =						[self.center_crop(image=a							,				size=a					) for image in images]

								if do_rescale:
										_UpperCamelCase         =						[self.rescale(image=a							,				scale=a					) for image in images]

								if do_normalize:
										_UpperCamelCase         =						[self.normalize(image=a							,				mean=a							,				std=a					) for image in images]

								_UpperCamelCase         =						[to_channel_dimension_format(a							,				a					) for image in images]

								_UpperCamelCase         =						{"""pixel_values""": images}
								return BatchFeature(data=a							,				tensor_type=a					)



