






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




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


            """simple docstring"""







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




       def 					a_					(					self      : Union[str, Any]					):


            """simple docstring"""







            __lowerCamelCase						:       Dict				   =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

            __lowerCamelCase						:       int				   =				self.get_config()

            return config, pixel_values, labels




       def 					a_					(					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 					a_					(					self      : Tuple					):


            """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 					a_					(					self      : Dict	,    A__      : List[str]	,    A__      : str	,    A__      : Dict					):


            """simple docstring"""







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




       def 					a_					(					self      : str					):


            """simple docstring"""







            __lowerCamelCase						:       Tuple				   =				self.prepare_config_and_inputs()
            (
                __lowerCamelCase 
            )						:       str				   =				config_and_inputs
            __lowerCamelCase						:       str				   =				{"pixel_values": pixel_values}
            return config, inputs_dict







@require_torch
class 	SCREAMING_SNAKE_CASE	(      snake_case__    ,   snake_case__    ,   unittest.TestCase  ):
       snake_case__    :     Optional[Any]   		=			(UperNetForSemanticSegmentation,) if is_torch_available() else ()
       snake_case__    :     str   		=			{'image-segmentation': UperNetForSemanticSegmentation} if is_torch_available() else {}
       snake_case__    :     List[str]   		=			False
       snake_case__    :     str   		=			False
       snake_case__    :     Optional[int]   		=			False
       snake_case__    :     Optional[int]   		=			False
       snake_case__    :     List[str]   		=			False
       snake_case__    :     Tuple   		=			False




       def 					a_					(					self      : int					):


            """simple docstring"""







            __lowerCamelCase						:       List[Any]				   =				UperNetModelTester(self					)
            __lowerCamelCase						:       Dict				   =				ConfigTester(self	,    config_class=lowercase_	,    has_text_modality=lowercase_	,    hidden_size=37					)




       def 					a_					(					self      : Tuple					):


            """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 					a_					(					self      : Union[str, Any]					):


            """simple docstring"""







            return




       def 					a_					(					self      : Dict					):


            """simple docstring"""







            __lowerCamelCase						:       List[Any]				   =				self.model_tester.prepare_config_and_inputs_for_common()

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

                 __lowerCamelCase						:       Union[str, Any]				   =				["pixel_values"]
                 self.assertListEqual(arg_names[:1]	,    lowercase_					)




       def 					a_					(					self      : Dict					):


            """simple docstring"""







            __lowerCamelCase						:       List[str]				   =				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 					a_					(					self      : Dict					):


            """simple docstring"""







            pass




       @unittest.skip(reason="""UperNet does not support input and output embeddings"""					)
       def 					a_					(					self      : Optional[Any]					):


            """simple docstring"""







            pass




       @unittest.skip(reason="""UperNet does not have a base model"""					)
       def 					a_					(					self      : int					):


            """simple docstring"""







            pass




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


            """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 					a_					(					self      : Union[str, Any]					):


            """simple docstring"""







            pass




       @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""					)
       def 					a_					(					self      : Dict					):


            """simple docstring"""







            pass




       def 					a_					(					self      : Optional[Any]					):


            """simple docstring"""







            def check_hidden_states_output(A__      : List[Any]	,    A__      : Optional[int]	,    A__      : Tuple					):
                 __lowerCamelCase						:       Optional[Any]				   =				model_class(lowercase_					)
                 model.to(lowercase_					)
                 model.eval()

                 with torch.no_grad():
                      __lowerCamelCase						:       Optional[int]				   =				model(**self._prepare_for_class(lowercase_	,    lowercase_					)					)

                 __lowerCamelCase						:       List[Any]				   =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 __lowerCamelCase						:       Optional[int]				   =				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]	,    )

            __lowerCamelCase						:       List[str]				   =				self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 __lowerCamelCase						:       Dict				   =				True
                 check_hidden_states_output(lowercase_	,    lowercase_	,    lowercase_					)

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

                 check_hidden_states_output(lowercase_	,    lowercase_	,    lowercase_					)




       def 					a_					(					self      : Any					):


            """simple docstring"""







            __lowerCamelCase						:       Any				   =				self.model_tester.prepare_config_and_inputs_for_common()

            __lowerCamelCase						:       Tuple				   =				_config_zero_init(lowercase_					)
            __lowerCamelCase						:       Optional[Any]				   =				_config_zero_init(configs_no_init.backbone_config					)
            for model_class in self.all_model_classes:
                 __lowerCamelCase						:       str				   =				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 					a_					(					self      : Tuple					):


            """simple docstring"""







            pass




       @slow
       def 					a_					(					self      : str					):


            """simple docstring"""







            for model_name in UPERNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 __lowerCamelCase						:       List[str]				   =				UperNetForSemanticSegmentation.from_pretrained(lowercase_					)
                 self.assertIsNotNone(lowercase_					)

def     __lowercase  ()   ->     Tuple:


     """simple docstring"""
     __lowerCamelCase						:       int				   =				hf_hub_download(
         repo_id="""hf-internal-testing/fixtures_ade20k""",						repo_type="""dataset""",						filename="""ADE_val_00000001.jpg"""     )
     __lowerCamelCase						:       str				   =				Image.open(__SCREAMING_SNAKE_CASE     ).convert("""RGB"""     )
     return image







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




       def 					a_					(					self      : str					):


            """simple docstring"""







            __lowerCamelCase						:       Tuple				   =				AutoImageProcessor.from_pretrained("""openmmlab/upernet-swin-tiny"""					)
            __lowerCamelCase						:       Optional[int]				   =				UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-swin-tiny"""					).to(lowercase_					)

            __lowerCamelCase						:       List[Any]				   =				prepare_img()
            __lowerCamelCase						:       Optional[int]				   =				processor(images=lowercase_	,    return_tensors="""pt"""					).to(lowercase_					)

            with torch.no_grad():
                 __lowerCamelCase						:       Dict				   =				model(**lowercase_					)

            __lowerCamelCase						:       List[Any]				   =				torch.Size((1, model.config.num_labels, 512, 512)					)
            self.assertEqual(outputs.logits.shape	,    lowercase_					)

            __lowerCamelCase						:       str				   =				torch.tensor(
                [[-7.5958, -7.5958, -7.4302], [-7.5958, -7.5958, -7.4302], [-7.4797, -7.4797, -7.3068]]					).to(lowercase_					)
            self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]	,    lowercase_	,    atol=1e-4					)					)




       def 					a_					(					self      : Any					):


            """simple docstring"""







            __lowerCamelCase						:       int				   =				AutoImageProcessor.from_pretrained("""openmmlab/upernet-convnext-tiny"""					)
            __lowerCamelCase						:       Tuple				   =				UperNetForSemanticSegmentation.from_pretrained("""openmmlab/upernet-convnext-tiny"""					).to(lowercase_					)

            __lowerCamelCase						:       Optional[Any]				   =				prepare_img()
            __lowerCamelCase						:       Optional[int]				   =				processor(images=lowercase_	,    return_tensors="""pt"""					).to(lowercase_					)

            with torch.no_grad():
                 __lowerCamelCase						:       Union[str, Any]				   =				model(**lowercase_					)

            __lowerCamelCase						:       Any				   =				torch.Size((1, model.config.num_labels, 512, 512)					)
            self.assertEqual(outputs.logits.shape	,    lowercase_					)

            __lowerCamelCase						:       List[str]				   =				torch.tensor(
                [[-8.8110, -8.8110, -8.6521], [-8.8110, -8.8110, -8.6521], [-8.7746, -8.7746, -8.6130]]					).to(lowercase_					)
            self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]	,    lowercase_	,    atol=1e-4					)					)











'''simple docstring'''

import shutil
import tempfile
import unittest

from transformers import ClapFeatureExtractor, ClapProcessor, RobertaTokenizer, RobertaTokenizerFast
from transformers.testing_utils import require_sentencepiece, require_torchaudio

from .test_feature_extraction_clap import floats_list







@require_torchaudio
@require_sentencepiece
class 	SCREAMING_SNAKE_CASE	(      unittest.TestCase  ):




       def 					a_					(					self      : str					):


            """simple docstring"""







            __lowerCamelCase						:       Any				   =				"""laion/clap-htsat-unfused"""
            __lowerCamelCase						:       List[Any]				   =				tempfile.mkdtemp()




       def 					a_					(					self      : Optional[int]	,    **A__      : Union[str, Any]					):


            """simple docstring"""







            return RobertaTokenizer.from_pretrained(self.checkpoint	,    **A__					)




       def 					a_					(					self      : str	,    **A__      : Any					):


            """simple docstring"""







            return ClapFeatureExtractor.from_pretrained(self.checkpoint	,    **A__					)




       def 					a_					(					self      : List[str]					):


            """simple docstring"""







            shutil.rmtree(self.tmpdirname					)




       def 					a_					(					self      : str					):


            """simple docstring"""







            __lowerCamelCase						:       Dict				   =				self.get_tokenizer()
            __lowerCamelCase						:       Union[str, Any]				   =				self.get_feature_extractor()

            __lowerCamelCase						:       Dict				   =				ClapProcessor(tokenizer=A__	,    feature_extractor=A__					)

            processor.save_pretrained(self.tmpdirname					)
            __lowerCamelCase						:       Optional[Any]				   =				ClapProcessor.from_pretrained(self.tmpdirname					)

            self.assertEqual(processor.tokenizer.get_vocab()	,    tokenizer.get_vocab()					)
            self.assertIsInstance(processor.tokenizer	,    A__					)

            self.assertEqual(processor.feature_extractor.to_json_string()	,    feature_extractor.to_json_string()					)
            self.assertIsInstance(processor.feature_extractor	,    A__					)




       def 					a_					(					self      : str					):


            """simple docstring"""







            __lowerCamelCase						:       str				   =				ClapProcessor(tokenizer=self.get_tokenizer()	,    feature_extractor=self.get_feature_extractor()					)
            processor.save_pretrained(self.tmpdirname					)

            __lowerCamelCase						:       Tuple				   =				self.get_tokenizer(bos_token="""(BOS)"""	,    eos_token="""(EOS)"""					)
            __lowerCamelCase						:       Any				   =				self.get_feature_extractor(do_normalize=A__	,    padding_value=1.0					)

            __lowerCamelCase						:       List[Any]				   =				ClapProcessor.from_pretrained(
                self.tmpdirname	,    bos_token="""(BOS)"""	,    eos_token="""(EOS)"""	,    do_normalize=A__	,    padding_value=1.0					)

            self.assertEqual(processor.tokenizer.get_vocab()	,    tokenizer_add_kwargs.get_vocab()					)
            self.assertIsInstance(processor.tokenizer	,    A__					)

            self.assertEqual(processor.feature_extractor.to_json_string()	,    feature_extractor_add_kwargs.to_json_string()					)
            self.assertIsInstance(processor.feature_extractor	,    A__					)




       def 					a_					(					self      : Optional[int]					):


            """simple docstring"""







            __lowerCamelCase						:       Dict				   =				self.get_feature_extractor()
            __lowerCamelCase						:       Tuple				   =				self.get_tokenizer()

            __lowerCamelCase						:       Optional[int]				   =				ClapProcessor(tokenizer=A__	,    feature_extractor=A__					)

            __lowerCamelCase						:       Dict				   =				floats_list((3, 1000)					)

            __lowerCamelCase						:       str				   =				feature_extractor(A__	,    return_tensors="""np"""					)
            __lowerCamelCase						:       Any				   =				processor(audios=A__	,    return_tensors="""np"""					)

            for key in input_feat_extract.keys():
                 self.assertAlmostEqual(input_feat_extract[key].sum()	,    input_processor[key].sum()	,    delta=1e-2					)




       def 					a_					(					self      : Any					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[Any]				   =				self.get_feature_extractor()
            __lowerCamelCase						:       int				   =				self.get_tokenizer()

            __lowerCamelCase						:       str				   =				ClapProcessor(tokenizer=A__	,    feature_extractor=A__					)

            __lowerCamelCase						:       int				   =				"""This is a test string"""

            __lowerCamelCase						:       Any				   =				processor(text=A__					)

            __lowerCamelCase						:       Any				   =				tokenizer(A__					)

            for key in encoded_tok.keys():
                 self.assertListEqual(encoded_tok[key]	,    encoded_processor[key]					)




       def 					a_					(					self      : List[Any]					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[int]				   =				self.get_feature_extractor()
            __lowerCamelCase						:       List[str]				   =				self.get_tokenizer()

            __lowerCamelCase						:       int				   =				ClapProcessor(tokenizer=A__	,    feature_extractor=A__					)

            __lowerCamelCase						:       Union[str, Any]				   =				[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

            __lowerCamelCase						:       int				   =				processor.batch_decode(A__					)
            __lowerCamelCase						:       List[Any]				   =				tokenizer.batch_decode(A__					)

            self.assertListEqual(A__	,    A__					)




       def 					a_					(					self      : str					):


            """simple docstring"""







            __lowerCamelCase						:       Any				   =				self.get_feature_extractor()
            __lowerCamelCase						:       List[Any]				   =				self.get_tokenizer()

            __lowerCamelCase						:       Any				   =				ClapProcessor(tokenizer=A__	,    feature_extractor=A__					)

            self.assertListEqual(
                processor.model_input_names[2:]	,    feature_extractor.model_input_names	,    msg="""`processor` and `feature_extractor` model input names do not match"""	,    )



