


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


       """simple docstring"""




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


             '''simple docstring'''



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





       def 		lowerCAmelCase  (     self							:    Dict ):


             '''simple docstring'''



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

             lowerCamelCase__	:       List[str]					=						None
             if self.use_labels:
                   lowerCamelCase__	:       Optional[int]					=						ids_tensor([self.batch_size]      ,   self.type_sequence_label_size )

             lowerCamelCase__	:       str					=						self.get_config()

             return config, pixel_values, labels





       def 		lowerCAmelCase  (     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 		lowerCAmelCase  (     self							:    str ):


             '''simple docstring'''



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





       def 		lowerCAmelCase  (     self							:    Union[str, Any]      ,   __lowerCamelCase							:    int      ,   __lowerCamelCase							:    Union[str, Any]      ,   __lowerCamelCase							:    int ):


             '''simple docstring'''



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





       def 		lowerCAmelCase  (     self							:    str ):


             '''simple docstring'''



             lowerCamelCase__	:       List[str]					=						self.prepare_config_and_inputs()
             (
                 (
                 lowerCamelCase__
             )					,     (
                 lowerCamelCase__
             )					,     (
                 lowerCamelCase__
             )					,     
             )	:       Optional[int]					=						config_and_inputs
             lowerCamelCase__	:       Union[str, Any]					=						{"pixel_values": pixel_values}
             return config, inputs_dict







@require_torch
class     _lowercase				(							lowercase__							,						lowercase__							,						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 		lowerCAmelCase  (     self							:    Union[str, Any] ):


             '''simple docstring'''



             lowerCamelCase__	:       int					=						UperNetModelTester(self )
             lowerCamelCase__	:       Any					=						ConfigTester(self      ,   config_class=__lowerCamelCase      ,   has_text_modality=__lowerCamelCase      ,   hidden_size=37 )





       def 		lowerCAmelCase  (     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 		lowerCAmelCase  (     self							:    Optional[Any] ):


             '''simple docstring'''



             return





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


             '''simple docstring'''



             lowerCamelCase__					,     lowerCamelCase__	:       Optional[int]					=						self.model_tester.prepare_config_and_inputs_for_common()

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

                   lowerCamelCase__	:       List[Any]					=						["pixel_values"]
                   self.assertListEqual(arg_names[:1]      ,   __lowerCamelCase )





       def 		lowerCAmelCase  (     self							:    List[str] ):


             '''simple docstring'''



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


             '''simple docstring'''



             pass





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


             '''simple docstring'''



             pass





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


             '''simple docstring'''



             pass





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


             '''simple docstring'''



             pass





       def 		lowerCAmelCase  (     self							:    Optional[int] ):


             '''simple docstring'''



             def check_hidden_states_output(__lowerCamelCase							:    Optional[Any]      ,   __lowerCamelCase							:    List[str]      ,   __lowerCamelCase							:    List[Any] ):
                   lowerCamelCase__	:       Dict					=						model_class(__lowerCamelCase )
                   model.to(__lowerCamelCase )
                   model.eval()

                   with torch.no_grad():
                         lowerCamelCase__	:       Tuple					=						model(**self._prepare_for_class(__lowerCamelCase      ,   __lowerCamelCase ) )

                   lowerCamelCase__	:       Any					=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                   lowerCamelCase__	:       Optional[Any]					=						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__	:       Union[str, Any]					=						self.model_tester.prepare_config_and_inputs_for_common()

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

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

                   check_hidden_states_output(__lowerCamelCase      ,   __lowerCamelCase      ,   __lowerCamelCase )





       def 		lowerCAmelCase  (     self							:    Tuple ):


             '''simple docstring'''



             lowerCamelCase__					,     lowerCamelCase__	:       Union[str, Any]					=						self.model_tester.prepare_config_and_inputs_for_common()

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


             '''simple docstring'''



             pass





       @slow
       def 		lowerCAmelCase  (     self							:    Union[str, Any] ):


             '''simple docstring'''



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



def    lowercase_	(	):

      """simple docstring"""




      lowerCamelCase__	:       Optional[int]					=						hf_hub_download(
          repo_id="hf-internal-testing/fixtures_ade20k"					,      repo_type="dataset"					,      filename="ADE_val_00000001.jpg"		)
      lowerCamelCase__	:       List[str]					=						Image.open(_A		).convert("RGB"		)
      return image







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


       """simple docstring"""




       def 		lowerCAmelCase  (     self							:    str ):


             '''simple docstring'''



             lowerCamelCase__	:       Union[str, Any]					=						AutoImageProcessor.from_pretrained("openmmlab/upernet-swin-tiny" )
             lowerCamelCase__	:       int					=						UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-swin-tiny" ).to(__lowerCamelCase )

             lowerCamelCase__	:       str					=						prepare_img()
             lowerCamelCase__	:       Any					=						processor(images=__lowerCamelCase      ,   return_tensors="pt" ).to(__lowerCamelCase )

             with torch.no_grad():
                   lowerCamelCase__	:       str					=						model(**__lowerCamelCase )

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

             lowerCamelCase__	:       Optional[int]					=						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(__lowerCamelCase )
             self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]      ,   __lowerCamelCase      ,   atol=1E-4 ) )





       def 		lowerCAmelCase  (     self							:    List[str] ):


             '''simple docstring'''



             lowerCamelCase__	:       Optional[Any]					=						AutoImageProcessor.from_pretrained("openmmlab/upernet-convnext-tiny" )
             lowerCamelCase__	:       Union[str, Any]					=						UperNetForSemanticSegmentation.from_pretrained("openmmlab/upernet-convnext-tiny" ).to(__lowerCamelCase )

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

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

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

             lowerCamelCase__	:       Optional[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(__lowerCamelCase )
             self.assertTrue(torch.allclose(outputs.logits[0, 0, :3, :3]      ,   __lowerCamelCase      ,   atol=1E-4 ) )






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_torch_available,
)


A   :					Optional[int]	=      {
    "configuration_speecht5": [
        "SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP",
        "SpeechT5Config",
        "SpeechT5HifiGanConfig",
    ],
    "feature_extraction_speecht5": ["SpeechT5FeatureExtractor"],
    "processing_speecht5": ["SpeechT5Processor"],
}

try:
    if not is_sentencepiece_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    A   :					List[Any]	=      ["SpeechT5Tokenizer"]

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    A   :					List[str]	=      [
        "SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST",
        "SpeechT5ForSpeechToText",
        "SpeechT5ForSpeechToSpeech",
        "SpeechT5ForTextToSpeech",
        "SpeechT5Model",
        "SpeechT5PreTrainedModel",
        "SpeechT5HifiGan",
    ]

if TYPE_CHECKING:
    from .configuration_speechta import (
        SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP,
        SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP,
        SpeechTaConfig,
        SpeechTaHifiGanConfig,
    )
    from .feature_extraction_speechta import SpeechTaFeatureExtractor
    from .processing_speechta import SpeechTaProcessor

    try:
        if not is_sentencepiece_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .tokenization_speechta import SpeechTaTokenizer

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_speechta import (
            SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST,
            SpeechTaForSpeechToSpeech,
            SpeechTaForSpeechToText,
            SpeechTaForTextToSpeech,
            SpeechTaHifiGan,
            SpeechTaModel,
            SpeechTaPreTrainedModel,
        )

else:
    import sys

    A   :					Any	=      _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


