import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


UpperCAmelCase_			    =							get_logger(__name__)




class  __magic_name__  :





   """simple docstring"""




   def __init__(	self					:  List[Any]		,  _lowercase					:  Optional[str] = None							):



    """simple docstring"""



    _UpperCamelCase:     List[str]							= (
        os.path.join(_lowercase		,  config.EXTRACTED_DATASETS_DIR							) if cache_dir else config.EXTRACTED_DATASETS_PATH
    )
    _UpperCamelCase:     Union[str, Any]							= Extractor



   def   lowerCAmelCase						(	self					:  Dict		,  _lowercase					:  str							):



    """simple docstring"""



    from .file_utils import hash_url_to_filename

    # Path where we extract compressed archives
    # We extract in the cache dir, and get the extracted path name by hashing the original path"
    _UpperCamelCase:     List[str]							= os.path.abspath(_lowercase							)
    return os.path.join(self.extract_dir		,  hash_url_to_filename(_lowercase							)							)



   def   lowerCAmelCase						(	self					:  Optional[int]		,  _lowercase					:  str		,  _lowercase					:  bool							):



    """simple docstring"""



    return force_extract or (
        not os.path.isfile(_lowercase							) and not (os.path.isdir(_lowercase							) and os.listdir(_lowercase							))
    )



   def   lowerCAmelCase						(	self					:  List[Any]		,  _lowercase					:  str		,  _lowercase					:  bool = False							):



    """simple docstring"""



    _UpperCamelCase:     List[str]							= self.extractor.infer_extractor_format(_lowercase							)
    if not extractor_format:
     return input_path
    _UpperCamelCase:     List[str]							= self._get_output_path(_lowercase							)
    if self._do_extract(_lowercase		,  _lowercase							):
     self.extractor.extract(_lowercase		,  _lowercase		,  _lowercase							)
    return output_path




class  __magic_name__  (		__a    ):





   """simple docstring"""




   @classmethod
   @abstractmethod
   def   lowerCAmelCase						(	cls					:  Tuple		,  _lowercase					:  Union[Path, str]		,  **_lowercase					:  Any							):



    """simple docstring"""



    ...



   @staticmethod
   @abstractmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]							):



    """simple docstring"""



    ...




class  __magic_name__  (		__a      ,	__a    ):





   """simple docstring"""




   lowerCAmelCase      :    List[bytes]  			=   []



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  int							):



    """simple docstring"""



    with open(_lowercase		,  '''rb'''							) as f:
     return f.read(_lowercase							)



   @classmethod
   def   lowerCAmelCase						(	cls					:  Tuple		,  _lowercase					:  Union[Path, str]		,  _lowercase					:  bytes = b""							):



    """simple docstring"""



    if not magic_number:
     _UpperCamelCase:     List[str]							= max(len(_lowercase							) for cls_magic_number in cls.magic_numbers							)
     try:
      _UpperCamelCase:     List[Any]							= cls.read_magic_number(_lowercase		,  _lowercase							)
     except OSError:
      return False
    return any(magic_number.startswith(_lowercase							) for cls_magic_number in cls.magic_numbers							)




class  __magic_name__  (		__a    ):





   """simple docstring"""




   @classmethod
   def   lowerCAmelCase						(	cls					:  Union[str, Any]		,  _lowercase					:  Union[Path, str]		,  **_lowercase					:  Tuple							):



    """simple docstring"""



    return tarfile.is_tarfile(_lowercase							)



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[str, Any]		,  _lowercase					:  Optional[Any]							):



    """simple docstring"""



    def resolved(_lowercase					:  str							) -> str:
     return os.path.realpath(os.path.abspath(_lowercase							)							)

    def badpath(_lowercase					:  str		,  _lowercase					:  str							) -> bool:
     # joinpath will ignore base if path is absolute
     return not resolved(os.path.join(_lowercase		,  _lowercase							)							).startswith(_lowercase							)

    def badlink(_lowercase					:  str		,  _lowercase					:  str							) -> bool:
     # Links are interpreted relative to the directory containing the link
     _UpperCamelCase:     Any							= resolved(os.path.join(_lowercase		,  os.path.dirname(info.name							)							)							)
     return badpath(info.linkname		,  base=_lowercase							)

    _UpperCamelCase:     List[Any]							= resolved(_lowercase							)

    for finfo in members:
     if badpath(finfo.name		,  _lowercase							):
      logger.error(f"""Extraction of {finfo.name} is blocked (illegal path)"""							)
     elif finfo.issym() and badlink(_lowercase		,  _lowercase							):
      logger.error(f"""Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}"""							)
     elif finfo.islnk() and badlink(_lowercase		,  _lowercase							):
      logger.error(f"""Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}"""							)
     else:
      yield finfo



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]							):



    """simple docstring"""



    os.makedirs(_lowercase		,  exist_ok=_lowercase							)
    _UpperCamelCase:     Dict							= tarfile.open(_lowercase							)
    tar_file.extractall(_lowercase		,  members=TarExtractor.safemembers(_lowercase		,  _lowercase							)							)
    tar_file.close()




class  __magic_name__  (		__a    ):





   """simple docstring"""




   lowerCAmelCase      :    int  			=   [B'''\x1F\x8B''']



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]							):



    """simple docstring"""



    with gzip.open(_lowercase		,  '''rb'''							) as gzip_file:
     with open(_lowercase		,  '''wb'''							) as extracted_file:
      shutil.copyfileobj(_lowercase		,  _lowercase							)




class  __magic_name__  (		__a    ):





   """simple docstring"""




   lowerCAmelCase      :    Any  			=   [
       B'''PK\x03\x04''',
       B'''PK\x05\x06''',  # empty archive
       B'''PK\x07\x08''',  # spanned archive
   ]



   @classmethod
   def   lowerCAmelCase						(	cls					:  str		,  _lowercase					:  Union[Path, str]		,  _lowercase					:  bytes = b""							):



    """simple docstring"""



    if super().is_extractable(_lowercase		,  magic_number=_lowercase							):
     return True
    try:
     # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
     # From: https://github.com/python/cpython/pull/5053
     from zipfile import (
         _CD_SIGNATURE,
         _ECD_DISK_NUMBER,
         _ECD_DISK_START,
         _ECD_ENTRIES_TOTAL,
         _ECD_OFFSET,
         _ECD_SIZE,
         _EndRecData,
         sizeCentralDir,
         stringCentralDir,
         structCentralDir,
     )

     with open(_lowercase		,  '''rb'''							) as fp:
      _UpperCamelCase:     Tuple							= _EndRecData(_lowercase							)
      if endrec:
       if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
        return True  # Empty zipfiles are still zipfiles
       elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
        fp.seek(endrec[_ECD_OFFSET]							)  # Central directory is on the same disk
        if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
         _UpperCamelCase:     Any							= fp.read(_lowercase							)  # CD is where we expect it to be
         if len(_lowercase							) == sizeCentralDir:
          _UpperCamelCase:     Any							= struct.unpack(_lowercase		,  _lowercase							)  # CD is the right size
          if centdir[_CD_SIGNATURE] == stringCentralDir:
           return True  # First central directory entry  has correct magic number
     return False
    except Exception:  # catch all errors in case future python versions change the zipfile internals
     return False



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]							):



    """simple docstring"""



    os.makedirs(_lowercase		,  exist_ok=_lowercase							)
    with zipfile.ZipFile(_lowercase		,  '''r'''							) as zip_file:
     zip_file.extractall(_lowercase							)
     zip_file.close()




class  __magic_name__  (		__a    ):





   """simple docstring"""




   lowerCAmelCase      :    Optional[Any]  			=   [B'''\xFD\x37\x7A\x58\x5A\x00''']



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]							):



    """simple docstring"""



    with lzma.open(_lowercase							) as compressed_file:
     with open(_lowercase		,  '''wb'''							) as extracted_file:
      shutil.copyfileobj(_lowercase		,  _lowercase							)




class  __magic_name__  (		__a    ):





   """simple docstring"""




   lowerCAmelCase      :    Union[str, Any]  			=   [B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]							):



    """simple docstring"""



    if not config.RARFILE_AVAILABLE:
     raise ImportError('''Please pip install rarfile'''							)
    import rarfile

    os.makedirs(_lowercase		,  exist_ok=_lowercase							)
    _UpperCamelCase:     int							= rarfile.RarFile(_lowercase							)
    rf.extractall(_lowercase							)
    rf.close()




class  __magic_name__  (		__a    ):





   """simple docstring"""




   lowerCAmelCase      :    Dict  			=   [B'''\x28\xb5\x2F\xFD''']



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]							):



    """simple docstring"""



    if not config.ZSTANDARD_AVAILABLE:
     raise ImportError('''Please pip install zstandard'''							)
    import zstandard as zstd

    _UpperCamelCase:     Optional[int]							= zstd.ZstdDecompressor()
    with open(_lowercase		,  '''rb'''							) as ifh, open(_lowercase		,  '''wb'''							) as ofh:
     dctx.copy_stream(_lowercase		,  _lowercase							)




class  __magic_name__  (		__a    ):





   """simple docstring"""




   lowerCAmelCase      :    str  			=   [B'''\x42\x5A\x68''']



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]							):



    """simple docstring"""



    with bza.open(_lowercase		,  '''rb'''							) as compressed_file:
     with open(_lowercase		,  '''wb'''							) as extracted_file:
      shutil.copyfileobj(_lowercase		,  _lowercase							)




class  __magic_name__  (		__a    ):





   """simple docstring"""




   lowerCAmelCase      :    Optional[int]  			=   [B'''\x37\x7A\xBC\xAF\x27\x1C''']



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]							):



    """simple docstring"""



    if not config.PY7ZR_AVAILABLE:
     raise ImportError('''Please pip install py7zr'''							)
    import pyazr

    os.makedirs(_lowercase		,  exist_ok=_lowercase							)
    with pyazr.SevenZipFile(_lowercase		,  '''r'''							) as archive:
     archive.extractall(_lowercase							)




class  __magic_name__  (		__a    ):





   """simple docstring"""




   lowerCAmelCase      :    Union[str, Any]  			=   [B'''\x04\x22\x4D\x18''']



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]							):



    """simple docstring"""



    if not config.LZ4_AVAILABLE:
     raise ImportError('''Please pip install lz4'''							)
    import lza.frame

    with lza.frame.open(_lowercase		,  '''rb'''							) as compressed_file:
     with open(_lowercase		,  '''wb'''							) as extracted_file:
      shutil.copyfileobj(_lowercase		,  _lowercase							)




class  __magic_name__  :





   """simple docstring"""




   lowerCAmelCase      :    Dict[str, Type[BaseExtractor]]  			=   {
       "tar": TarExtractor,
       "gzip": GzipExtractor,
       "zip": ZipExtractor,
       "xz": XzExtractor,
       "rar": RarExtractor,
       "zstd": ZstdExtractor,
       "bz2": BzipaExtractor,
       "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
       "lz4": LzaExtractor,  # <Added version="2.4.0"/>
   }



   @classmethod
   def   lowerCAmelCase						(	cls					:  Optional[Any]							):



    """simple docstring"""



    return max(
        len(_lowercase							)
        for extractor in cls.extractors.values()
        if issubclass(_lowercase		,  _lowercase							)
        for extractor_magic_number in extractor.magic_numbers							)



   @staticmethod
   def   lowerCAmelCase						(	_lowercase					:  Union[Path, str]		,  _lowercase					:  int							):



    """simple docstring"""



    try:
     return MagicNumberBaseExtractor.read_magic_number(_lowercase		,  magic_number_length=_lowercase							)
    except OSError:
     return b""



   @classmethod
   def   lowerCAmelCase						(	cls					:  List[Any]		,  _lowercase					:  Union[Path, str]		,  _lowercase					:  bool = False							):



    """simple docstring"""



    warnings.warn(
        '''Method \'is_extractable\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '''
        '''Use \'infer_extractor_format\' instead.'''		,  category=_lowercase		,  )
    _UpperCamelCase:     Union[str, Any]							= cls.infer_extractor_format(_lowercase							)
    if extractor_format:
     return True if not return_extractor else (True, cls.extractors[extractor_format])
    return False if not return_extractor else (False, None)



   @classmethod
   def   lowerCAmelCase						(	cls					:  Any		,  _lowercase					:  Union[Path, str]							):  # <Added version="2.4.0"/>



    """simple docstring"""



    _UpperCamelCase:     Optional[Any]							= cls._get_magic_number_max_length()
    _UpperCamelCase:     Dict							= cls._read_magic_number(_lowercase		,  _lowercase							)
    for extractor_format, extractor in cls.extractors.items():
     if extractor.is_extractable(_lowercase		,  magic_number=_lowercase							):
      return extractor_format



   @classmethod
   def   lowerCAmelCase						(	cls					:  Optional[int]		,  _lowercase					:  Union[Path, str]		,  _lowercase					:  Union[Path, str]		,  _lowercase					:  Optional[str] = None		,  _lowercase					:  Optional[BaseExtractor] = "deprecated"		,  ):



    """simple docstring"""



    os.makedirs(os.path.dirname(_lowercase							)		,  exist_ok=_lowercase							)
    # Prevent parallel extractions
    _UpperCamelCase:     Optional[int]							= str(Path(_lowercase							).with_suffix('''.lock'''							)							)
    with FileLock(_lowercase							):
     shutil.rmtree(_lowercase		,  ignore_errors=_lowercase							)
     if extractor_format or extractor != "deprecated":
      if extractor != "deprecated" or not isinstance(_lowercase		,  _lowercase							):  # passed as positional arg
       warnings.warn(
           '''Parameter \'extractor\' was deprecated in version 2.4.0 and will be removed in 3.0.0. '''
           '''Use \'extractor_format\' instead.'''		,  category=_lowercase		,  )
       _UpperCamelCase:     Tuple							= extractor if extractor != '''deprecated''' else extractor_format
      else:
       _UpperCamelCase:     Any							= cls.extractors[extractor_format]
      return extractor.extract(_lowercase		,  _lowercase							)
     else:
      warnings.warn(
          '''Parameter \'extractor_format\' was made required in version 2.4.0 and not passing it will raise an '''
          '''exception in 3.0.0.'''		,  category=_lowercase		,  )
      for extractor in cls.extractors.values():
       if extractor.is_extractable(_lowercase							):
        return extractor.extract(_lowercase		,  _lowercase							)
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  __magic_name__  :





   """simple docstring"""




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



    """simple docstring"""



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



   def   lowerCAmelCase						(	self					:  Optional[Any]							):



    """simple docstring"""



    _UpperCamelCase:     Any							= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

    _UpperCamelCase:     Union[str, Any]							= self.get_config()

    return config, pixel_values, labels



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



    """simple docstring"""



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



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



    """simple docstring"""



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




@require_torch
class  __magic_name__  (		__a      ,	__a      ,	unittest.TestCase    ):





   """simple docstring"""




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



   def   lowerCAmelCase						(	self					:  Dict							):



    """simple docstring"""



    _UpperCamelCase:     Optional[int]							= UperNetModelTester(self							)
    _UpperCamelCase:     List[str]							= ConfigTester(self		,  config_class=_lowercase		,  has_text_modality=_lowercase		,  hidden_size=37							)



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



    """simple docstring"""



    return



   def   lowerCAmelCase						(	self					:  List[str]							):



    """simple docstring"""



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

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

     _UpperCamelCase:     List[Any]							= ['''pixel_values''']
     self.assertListEqual(arg_names[:1]		,  _lowercase							)



   def   lowerCAmelCase						(	self					:  Tuple							):



    """simple docstring"""



    _UpperCamelCase:     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   lowerCAmelCase						(	self					:  Tuple							):



    """simple docstring"""



    pass



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



    """simple docstring"""



    pass



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



    """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					:  Dict							):



    """simple docstring"""



    pass



   @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''							)
   def   lowerCAmelCase						(	self					:  Tuple							):



    """simple docstring"""



    pass



   def   lowerCAmelCase						(	self					:  Optional[Any]							):



    """simple docstring"""



    def check_hidden_states_output(_lowercase					:  List[str]		,  _lowercase					:  List[str]		,  _lowercase					:  List[str]							):
     _UpperCamelCase:     Any							= model_class(_lowercase							)
     model.to(_lowercase							)
     model.eval()

     with torch.no_grad():
      _UpperCamelCase:     Union[str, Any]							= model(**self._prepare_for_class(_lowercase		,  _lowercase							)							)

     _UpperCamelCase:     Optional[Any]							= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

     _UpperCamelCase:     List[str]							= 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]		,  )

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

    for model_class in self.all_model_classes:
     _UpperCamelCase:     Optional[int]							= True
     check_hidden_states_output(_lowercase		,  _lowercase		,  _lowercase							)

     # check that output_hidden_states also work using config
     del inputs_dict["output_hidden_states"]
     _UpperCamelCase:     Union[str, Any]							= True

     check_hidden_states_output(_lowercase		,  _lowercase		,  _lowercase							)



   def   lowerCAmelCase						(	self					:  Tuple							):



    """simple docstring"""



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

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



    """simple docstring"""



    pass



   @slow
   def   lowerCAmelCase						(	self					:  Optional[Any]							):



    """simple docstring"""



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




def       lowerCAmelCase_     (		)    ->				Dict:







 '''simple docstring'''
 _UpperCamelCase:     Any							= hf_hub_download(
     repo_id='''hf-internal-testing/fixtures_ade20k'''  ,					repo_type='''dataset'''  ,					filename='''ADE_val_00000001.jpg'''		)
 _UpperCamelCase:     Any							= Image.open(lowercase		).convert('''RGB'''		)
 return image





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





   """simple docstring"""




   def   lowerCAmelCase						(	self					:  Optional[Any]							):



    """simple docstring"""



    _UpperCamelCase:     Any							= AutoImageProcessor.from_pretrained('''openmmlab/upernet-swin-tiny'''							)
    _UpperCamelCase:     Optional[Any]							= UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-swin-tiny'''							).to(_lowercase							)

    _UpperCamelCase:     List[Any]							= prepare_img()
    _UpperCamelCase:     int							= processor(images=_lowercase		,  return_tensors='''pt'''							).to(_lowercase							)

    with torch.no_grad():
     _UpperCamelCase:     Any							= model(**_lowercase							)

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

    _UpperCamelCase:     Tuple							= 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   lowerCAmelCase						(	self					:  int							):



    """simple docstring"""



    _UpperCamelCase:     Tuple							= AutoImageProcessor.from_pretrained('''openmmlab/upernet-convnext-tiny'''							)
    _UpperCamelCase:     int							= UperNetForSemanticSegmentation.from_pretrained('''openmmlab/upernet-convnext-tiny'''							).to(_lowercase							)

    _UpperCamelCase:     int							= prepare_img()
    _UpperCamelCase:     Union[str, Any]							= processor(images=_lowercase		,  return_tensors='''pt'''							).to(_lowercase							)

    with torch.no_grad():
     _UpperCamelCase:     List[Any]							= model(**_lowercase							)

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

    _UpperCamelCase:     Optional[Any]							= 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							)							)