





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




   """simple docstring"""



   def __init__(					self					,  lowercase					,  lowercase=13					,  lowercase=32					,  lowercase=3					,  lowercase=4					,  lowercase=[10, 20, 30, 40]					,  lowercase=[2, 2, 3, 2]					,  lowercase=True					,  lowercase=True					,  lowercase=37					,  lowercase="gelu"					,  lowercase=10					,  lowercase=0.02					,  lowercase=["stage2", "stage3", "stage4"]					,  lowercase=3					,  lowercase=None					,  )			->						List[str]:







          '''simple docstring'''

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

   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          a__						:	List[str] =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          a__						:	int =				None
          if self.use_labels:
                 a__						:	Union[str, Any] =				ids_tensor([self.batch_size]					,  self.type_sequence_label_size)

          a__						:	Tuple =				self.get_config()

          return config, pixel_values, labels

   def 							__lowercase		(					self)			->						Optional[Any]:







          '''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)			->						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=lowercase					,  auxiliary_loss_weight=0.4					,  auxiliary_in_channels=40					,  auxiliary_channels=256					,  auxiliary_num_convs=1					,  auxiliary_concat_input=lowercase					,  loss_ignore_index=255					,  num_labels=self.num_labels					,  )

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase)			->						List[str]:







          '''simple docstring'''

          a__						:	Tuple =				UperNetForSemanticSegmentation(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	Optional[Any] =				model(lowercase)
          self.parent.assertEqual(
              result.logits.shape					,  (self.batch_size, self.num_labels, self.image_size, self.image_size))

   def 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

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





@require_torch
class  A__    (							__UpperCAmelCase ,  __UpperCAmelCase ,  unittest.TestCase	):




   """simple docstring"""



   __A   :				Tuple         =  (UperNetForSemanticSegmentation,) if is_torch_available() else ()
   __A   :				Union[str, Any]         =  {'''image-segmentation''': UperNetForSemanticSegmentation} if is_torch_available() else {}
   __A   :				Optional[Any]         =  False
   __A   :				Union[str, Any]         =  False
   __A   :				List[str]         =  False
   __A   :				Union[str, Any]         =  False
   __A   :				Any         =  False
   __A   :				List[Any]         =  False

   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          a__						:	Tuple =				UperNetModelTester(self)
          a__						:	List[str] =				ConfigTester(self					,  config_class=lowercase					,  has_text_modality=lowercase					,  hidden_size=37)

   def 							__lowercase		(					self)			->						str:







          '''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)			->						List[Any]:







          '''simple docstring'''

          return

   def 							__lowercase		(					self)			->						Dict:







          '''simple docstring'''

          a__ ,							a__						:	Optional[Any] =				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 a__						:	str =				model_class(lowercase)
                 a__						:	Optional[Any] =				inspect.signature(model.forward)
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 a__						:	List[Any] =				[*signature.parameters.keys()]

                 a__						:	str =				['pixel_values']
                 self.assertListEqual(arg_names[:1]					,  lowercase)

   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          a__						:	Optional[int] =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*lowercase)

   @unittest.skip(reason='UperNet does not use inputs_embeds')
   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          pass

   @unittest.skip(reason='UperNet does not support input and output embeddings')
   def 							__lowercase		(					self)			->						Dict:







          '''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)			->						List[str]:







          '''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)			->						List[Any]:







          '''simple docstring'''

          pass

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          def check_hidden_states_output(lowercase					,  lowercase					,  lowercase):
                 a__						:	Optional[int] =				model_class(lowercase)
                 model.to(lowercase)
                 model.eval()

                 with torch.no_grad():
                        a__						:	Dict =				model(**self._prepare_for_class(lowercase					,  lowercase))

                 a__						:	str =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 a__						:	Tuple =				self.model_tester.num_stages
                 self.assertEqual(len(lowercase)					,  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__ ,							a__						:	Any =				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 a__						:	List[Any] =				True
                 check_hidden_states_output(lowercase					,  lowercase					,  lowercase)

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 a__						:	Tuple =				True

                 check_hidden_states_output(lowercase					,  lowercase					,  lowercase)

   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          a__ ,							a__						:	Any =				self.model_tester.prepare_config_and_inputs_for_common()

          a__						:	List[Any] =				_config_zero_init(lowercase)
          a__						:	Dict =				_config_zero_init(configs_no_init.backbone_config)
          for model_class in self.all_model_classes:
                 a__						:	Any =				model_class(config=lowercase)
                 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)			->						str:







          '''simple docstring'''

          pass

   @slow
   def 							__lowercase		(					self)			->						Optional[Any]:







          '''simple docstring'''

          for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a__						:	Union[str, Any] =				UperNetForSemanticSegmentation.from_pretrained(lowercase)
                 self.assertIsNotNone(lowercase)



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





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




   """simple docstring"""



   def 							__lowercase		(					self)			->						Optional[Any]:







          '''simple docstring'''

          a__						:	Any =				AutoImageProcessor.from_pretrained('openmmlab/upernet-swin-tiny')
          a__						:	List[str] =				UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-swin-tiny').to(lowercase)

          a__						:	str =				prepare_img()
          a__						:	List[str] =				processor(images=lowercase					,  return_tensors='pt').to(lowercase)

          with torch.no_grad():
                 a__						:	List[str] =				model(**lowercase)

          a__						:	Optional[int] =				torch.Size((1, model.config.num_labels, 512, 512))
          self.assertEqual(outputs.logits.shape					,  lowercase)

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

   def 							__lowercase		(					self)			->						Tuple:







          '''simple docstring'''

          a__						:	Union[str, Any] =				AutoImageProcessor.from_pretrained('openmmlab/upernet-convnext-tiny')
          a__						:	Tuple =				UperNetForSemanticSegmentation.from_pretrained('openmmlab/upernet-convnext-tiny').to(lowercase)

          a__						:	Optional[int] =				prepare_img()
          a__						:	Any =				processor(images=lowercase					,  return_tensors='pt').to(lowercase)

          with torch.no_grad():
                 a__						:	Any =				model(**lowercase)

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

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



"""simple docstring"""







from collections import Counter
from pathlib import Path
from typing import Optional, Tuple

import yaml







class        UpperCamelCase		(			yaml.SafeLoader  ):
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase			)	->      Optional[int]:


        '''simple docstring'''


        lowercase_	:				str													=	[self.constructed_objects[key_node] for key_node, _ in node.value]
        lowercase_	:				str													=	[tuple(__UpperCamelCase			) if isinstance(__UpperCamelCase     ,__UpperCamelCase			) else key for key in keys]
        lowercase_	:				List[Any]													=	Counter(__UpperCamelCase			)
        lowercase_	:				str													=	[key for key in counter if counter[key] > 1]
        if duplicate_keys:
             raise TypeError(f'''Got duplicate yaml keys: {duplicate_keys}'''			)







   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase=False			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	super().construct_mapping(__UpperCamelCase     ,deep=__UpperCamelCase			)
        self._check_no_duplicates_on_constructed_node(__UpperCamelCase			)
        return mapping






def 			lowercase__(       __SCREAMING_SNAKE_CASE							:     str      ):
     lowercase_	:				Tuple													=	list(readme_content.splitlines()      )
     if full_content and full_content[0] == "---" and "---" in full_content[1:]:
          lowercase_	:				Dict													=	full_content[1:].index('---'      ) + 1
          lowercase_	:				Optional[int]													=	'\n'.join(full_content[1:sep_idx]      )
          return yamlblock, "\n".join(full_content[sep_idx + 1 :]      )

     return None, "\n".join(__SCREAMING_SNAKE_CASE      )







class        UpperCamelCase		(			lowercase_  ):
   # class attributes
   lowercase							=  {'train_eval_index'}  # train-eval-index in the YAML metadata
   @classmethod
   def 			_UpperCAmelCase   (			cls     ,__UpperCamelCase			)	->      "DatasetMetadata":


        '''simple docstring'''


        with open(__UpperCamelCase     ,encoding='utf-8'			) as readme_file:
             lowercase_							,  lowercase_	:				Optional[int]													=	_split_yaml_from_readme(readme_file.read()			)
        if yaml_string is not None:
             return cls.from_yaml_string(__UpperCamelCase			)
        else:
             return cls()
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase			)	->      List[Any]:


        '''simple docstring'''


        if path.exists():
             with open(__UpperCamelCase     ,encoding='utf-8'			) as readme_file:
                  lowercase_	:				Dict													=	readme_file.read()
        else:
             lowercase_	:				int													=	None
        lowercase_	:				Any													=	self._to_readme(__UpperCamelCase			)
        with open(__UpperCamelCase     ,'w'     ,encoding='utf-8'			) as readme_file:
             readme_file.write(__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase = None			)	->      str:


        '''simple docstring'''


        if readme_content is not None:
             lowercase_							,  lowercase_	:				Optional[Any]													=	_split_yaml_from_readme(__UpperCamelCase			)
             lowercase_	:				Optional[Any]													=	'---\n' + self.to_yaml_string() + '---\n' + content
        else:
             lowercase_	:				Tuple													=	'---\n' + self.to_yaml_string() + '---\n'
        return full_content
   @classmethod
   def 			_UpperCAmelCase   (			cls     ,__UpperCamelCase			)	->      "DatasetMetadata":


        '''simple docstring'''


        lowercase_	:				List[str]													=	yaml.load(__UpperCamelCase     ,Loader=_NoDuplicateSafeLoader			) or {}

        # Convert the YAML keys to DatasetMetadata fields
        lowercase_	:				Dict													=	{
            (key.replace('-'     ,'_'			) if key.replace('-'     ,'_'			) in cls._FIELDS_WITH_DASHES else key): value
            for key, value in metadata_dict.items()
        }
        return cls(**__UpperCamelCase			)







   def 			_UpperCAmelCase   (			self			)	->      str:


        '''simple docstring'''


        return yaml.safe_dump(
            {
                (key.replace('_'     ,'-'			) if key in self._FIELDS_WITH_DASHES else key): value
                for key, value in self.items()
            }     ,sort_keys=__UpperCamelCase     ,allow_unicode=__UpperCamelCase     ,encoding='utf-8'     ,).decode('utf-8'			)






__SCREAMING_SNAKE_CASE    	={
    "image-classification": [],
    "translation": [],
    "image-segmentation": [],
    "fill-mask": [],
    "automatic-speech-recognition": [],
    "token-classification": [],
    "sentence-similarity": [],
    "audio-classification": [],
    "question-answering": [],
    "summarization": [],
    "zero-shot-classification": [],
    "table-to-text": [],
    "feature-extraction": [],
    "other": [],
    "multiple-choice": [],
    "text-classification": [],
    "text-to-image": [],
    "text2text-generation": [],
    "zero-shot-image-classification": [],
    "tabular-classification": [],
    "tabular-regression": [],
    "image-to-image": [],
    "tabular-to-text": [],
    "unconditional-image-generation": [],
    "text-retrieval": [],
    "text-to-speech": [],
    "object-detection": [],
    "audio-to-audio": [],
    "text-generation": [],
    "conversational": [],
    "table-question-answering": [],
    "visual-question-answering": [],
    "image-to-text": [],
    "reinforcement-learning": [],
    "voice-activity-detection": [],
    "time-series-forecasting": [],
    "document-question-answering": [],
}


if __name__ == "__main__":
       from argparse import ArgumentParser

       __SCREAMING_SNAKE_CASE    	=ArgumentParser(usage="Validate the yaml metadata block of a README.md file.")
       ap.add_argument("readme_filepath")
       __SCREAMING_SNAKE_CASE    	=ap.parse_args()

       __SCREAMING_SNAKE_CASE    	=Path(args.readme_filepath)
       __SCREAMING_SNAKE_CASE    	=DatasetMetadata.from_readme(readme_filepath)
       print(dataset_metadata)
       dataset_metadata.to_readme(readme_filepath)

