





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

  """simple docstring"""


  def __init__(							self					:						List[str]   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						Dict=1_3   ,    lowerCAmelCase_					:						str=3_2   ,    lowerCAmelCase_					:						Optional[Any]=3   ,    lowerCAmelCase_					:						Any=4   ,    lowerCAmelCase_					:						str=[1_0, 2_0, 3_0, 4_0]   ,    lowerCAmelCase_					:						Tuple=[2, 2, 3, 2]   ,    lowerCAmelCase_					:						str=True   ,    lowerCAmelCase_					:						str=True   ,    lowerCAmelCase_					:						Optional[int]=3_7   ,    lowerCAmelCase_					:						Dict="gelu"   ,    lowerCAmelCase_					:						List[Any]=1_0   ,    lowerCAmelCase_					:						str=0.02   ,    lowerCAmelCase_					:						Dict=["stage2", "stage3", "stage4"]   ,    lowerCAmelCase_					:						Dict=3   ,    lowerCAmelCase_					:						List[Any]=None   ,    )				->		int:
     __lowerCAmelCase				      =      parent
     __lowerCAmelCase				      =      batch_size
     __lowerCAmelCase				      =      image_size
     __lowerCAmelCase				      =      num_channels
     __lowerCAmelCase				      =      num_stages
     __lowerCAmelCase				      =      hidden_sizes
     __lowerCAmelCase				      =      depths
     __lowerCAmelCase				      =      is_training
     __lowerCAmelCase				      =      use_labels
     __lowerCAmelCase				      =      intermediate_size
     __lowerCAmelCase				      =      hidden_act
     __lowerCAmelCase				      =      type_sequence_label_size
     __lowerCAmelCase				      =      initializer_range
     __lowerCAmelCase				      =      out_features
     __lowerCAmelCase				      =      num_labels
     __lowerCAmelCase				      =      scope
     __lowerCAmelCase				      =      num_stages






  def 							lowercase						(							self					:						Dict	)				->		List[str]:
     __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.type_sequence_label_size	)

     __lowerCAmelCase				      =      self.get_config()

     return config, pixel_values, labels






  def 							lowercase						(							self					:						List[str]	)				->		Union[str, Any]:
     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					:						Dict	)				->		List[str]:
     return UperNetConfig(
         backbone_config=self.get_backbone_config()   ,    hidden_size=5_1_2   ,    pool_scales=[1, 2, 3, 6]   ,    use_auxiliary_head=lowerCAmelCase_   ,    auxiliary_loss_weight=0.4   ,    auxiliary_in_channels=4_0   ,    auxiliary_channels=2_5_6   ,    auxiliary_num_convs=1   ,    auxiliary_concat_input=lowerCAmelCase_   ,    loss_ignore_index=2_5_5   ,    num_labels=self.num_labels   ,    )






  def 							lowercase						(							self					:						List[Any]   ,    lowerCAmelCase_					:						Tuple   ,    lowerCAmelCase_					:						Union[str, Any]   ,    lowerCAmelCase_					:						int	)				->		Optional[Any]:
     __lowerCAmelCase				      =      UperNetForSemanticSegmentation(config=lowerCAmelCase_	)
     model.to(lowerCAmelCase_	)
     model.eval()
     __lowerCAmelCase				      =      model(lowerCAmelCase_	)
     self.parent.assertEqual(
         result.logits.shape   ,    (self.batch_size, self.num_labels, self.image_size, self.image_size)	)






  def 							lowercase						(							self					:						Union[str, Any]	)				->		Union[str, 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 							_UpperCAmelCase       (       _UpperCamelCase						,       _UpperCamelCase						,       unittest.TestCase       ):

  """simple docstring"""


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






  def 							lowercase						(							self					:						Optional[int]	)				->		Dict:
     __lowerCAmelCase				      =      UperNetModelTester(self	)
     __lowerCAmelCase				      =      ConfigTester(self   ,    config_class=lowerCAmelCase_   ,    has_text_modality=lowerCAmelCase_   ,    hidden_size=3_7	)






  def 							lowercase						(							self					:						List[str]	)				->		int:
     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					:						Tuple	)				->		Union[str, Any]:
     return






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

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






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






  @unittest.skip(reason='UperNet does not use inputs_embeds'	)
  def 							lowercase						(							self					:						Optional[int]	)				->		Dict:
     pass






  @unittest.skip(reason='UperNet does not support input and output embeddings'	)
  def 							lowercase						(							self					:						Optional[Any]	)				->		Dict:
     pass






  @unittest.skip(reason='UperNet does not have a base model'	)
  def 							lowercase						(							self					:						Optional[int]	)				->		List[Any]:
     pass






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






  @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'	)
  def 							lowercase						(							self					:						Tuple	)				->		List[Any]:
     pass






  def 							lowercase						(							self					:						Union[str, Any]	)				->		Tuple:
     def check_hidden_states_output(lowerCAmelCase_					:						List[str]   ,    lowerCAmelCase_					:						int   ,    lowerCAmelCase_					:						Optional[Any]	):
        __lowerCAmelCase				      =      model_class(lowerCAmelCase_	)
        model.to(lowerCAmelCase_	)
        model.eval()

        with torch.no_grad():
           __lowerCAmelCase				      =      model(**self._prepare_for_class(lowerCAmelCase_   ,    lowerCAmelCase_	)	)

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

        __lowerCAmelCase				      =      self.model_tester.num_stages
        self.assertEqual(len(lowerCAmelCase_	)   ,    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]   ,    )

     __lowerCAmelCase      ,      __lowerCAmelCase				      =      self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __lowerCAmelCase				      =      True
        check_hidden_states_output(lowerCAmelCase_   ,    lowerCAmelCase_   ,    lowerCAmelCase_	)

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

        check_hidden_states_output(lowerCAmelCase_   ,    lowerCAmelCase_   ,    lowerCAmelCase_	)






  def 							lowercase						(							self					:						Any	)				->		Tuple:
     __lowerCAmelCase      ,      __lowerCAmelCase				      =      self.model_tester.prepare_config_and_inputs_for_common()

     __lowerCAmelCase				      =      _config_zero_init(lowerCAmelCase_	)
     __lowerCAmelCase				      =      _config_zero_init(configs_no_init.backbone_config	)
     for model_class in self.all_model_classes:
        __lowerCAmelCase				      =      model_class(config=lowerCAmelCase_	)
        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					:						Any	)				->		int:
     pass






  @slow
  def 							lowercase						(							self					:						Optional[int]	)				->		Optional[int]:
     for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCAmelCase				      =      UperNetForSemanticSegmentation.from_pretrained(lowerCAmelCase_	)
        self.assertIsNotNone(lowerCAmelCase_	)





def     a_       (					):
   __lowerCAmelCase				      =      hf_hub_download(
       repo_id='hf-internal-testing/fixtures_ade20k',      repo_type='dataset',      filename='ADE_val_00000001.jpg'      )
   __lowerCAmelCase				      =      Image.open(lowerCAmelCase_      ).convert('RGB'      )
   return image




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

  """simple docstring"""


  def 							lowercase						(							self					:						Dict	)				->		Union[str, Any]:
     __lowerCAmelCase				      =      AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny'	)
     __lowerCAmelCase				      =      UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny'	).to(lowerCAmelCase_	)

     __lowerCAmelCase				      =      prepare_img()
     __lowerCAmelCase				      =      processor(images=lowerCAmelCase_   ,    return_tensors='pt'	).to(lowerCAmelCase_	)

     with torch.no_grad():
        __lowerCAmelCase				      =      model(**lowerCAmelCase_	)

     __lowerCAmelCase				      =      torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)	)
     self.assertEqual(outputs.logits.shape   ,    lowerCAmelCase_	)

     __lowerCAmelCase				      =      torch.tensor(
         [[-7.59_58, -7.59_58, -7.43_02], [-7.59_58, -7.59_58, -7.43_02], [-7.47_97, -7.47_97, -7.30_68]]	).to(lowerCAmelCase_	)
     self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]   ,    lowerCAmelCase_   ,    atol=1e-4	)	)






  def 							lowercase						(							self					:						List[Any]	)				->		List[str]:
     __lowerCAmelCase				      =      AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny'	)
     __lowerCAmelCase				      =      UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny'	).to(lowerCAmelCase_	)

     __lowerCAmelCase				      =      prepare_img()
     __lowerCAmelCase				      =      processor(images=lowerCAmelCase_   ,    return_tensors='pt'	).to(lowerCAmelCase_	)

     with torch.no_grad():
        __lowerCAmelCase				      =      model(**lowerCAmelCase_	)

     __lowerCAmelCase				      =      torch.Size((1, model.config.num_labels, 5_1_2, 5_1_2)	)
     self.assertEqual(outputs.logits.shape   ,    lowerCAmelCase_	)

     __lowerCAmelCase				      =      torch.tensor(
         [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]]	).to(lowerCAmelCase_	)
     self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]   ,    lowerCAmelCase_   ,    atol=1e-4	)	)









UpperCAmelCase__      			=						'''Input must be a string of 8 numbers plus letter'''
UpperCAmelCase__      			=						'''TRWAGMYFPDXBNJZSQVHLCKE'''







def     a_   (__A      )				->						bool:



					"""simple docstring"""

					if not isinstance(__A				,       __A      ):
										__a					:						Any      =					f'Expected string as input, found {type(__A      ).__name__}'
										raise TypeError(__A      )

					__a					:						int      =					spanish_id.replace("-"				,       ""      ).upper()
					if len(__A      ) != 9:
										raise ValueError(__A      )

					try:
										__a					:						Tuple      =					int(spanish_id_clean[0:8]      )
										__a					:						Optional[int]      =					spanish_id_clean[8]
					except ValueError as ex:
										raise ValueError(__A      ) from ex

					if letter.isdigit():
										raise ValueError(__A      )

					return letter == LOOKUP_LETTERS[number % 23]


if __name__ == "__main__":
			import doctest

			doctest.testmod()





