

"""simple docstring"""




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

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






   '''simple docstring'''
   UpperCAmelCase__					:  Dict					   =					(
       os.path.join(UpperCamelCase_					,config.EXTRACTED_DATASETS_DIR    ) if cache_dir else config.EXTRACTED_DATASETS_PATH
   )
   UpperCAmelCase__					:  Optional[int]					   =					Extractor

  def    __lowercase       (  self		:			List[str]					,A		:			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__					:  int					   =					os.path.abspath(UpperCamelCase_    )
   return os.path.join(self.extract_dir					,hash_url_to_filename(UpperCamelCase_    )    )

  def    __lowercase       (  self		:			str					,A		:			str					,A		:			bool    ):






   '''simple docstring'''
   return force_extract or (
       not os.path.isfile(UpperCamelCase_    ) and not (os.path.isdir(UpperCamelCase_    ) and os.listdir(UpperCamelCase_    ))
   )




  def    __lowercase       (  self		:			str					,A		:			str					,A		:			bool = False    ):






   '''simple docstring'''
   UpperCAmelCase__					:  int					   =					self.extractor.infer_extractor_format(UpperCamelCase_    )
   if not extractor_format:
    return input_path
   UpperCAmelCase__					:  Tuple					   =					self._get_output_path(UpperCamelCase_    )
   if self._do_extract(UpperCamelCase_					,UpperCamelCase_    ):
    self.extractor.extract(UpperCamelCase_					,UpperCamelCase_					,UpperCamelCase_    )
   return output_path







class      __lowercase			(    __lowerCamelCase					):

  @classmethod
  @abstractmethod
  def    __lowercase       (  cls		:			Optional[Any]					,A		:			Union[Path, str]					,**A		:			Optional[int]    ):






   '''simple docstring'''
   ...




  @staticmethod
  @abstractmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			Union[Path, str]    ):






   '''simple docstring'''
   ...







class      __lowercase			(    __lowerCamelCase	,			__lowerCamelCase					):
  snake_case_				       =       []

  @staticmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			int    ):






   '''simple docstring'''
   with open(UpperCamelCase_					,"""rb"""    ) as f:
    return f.read(UpperCamelCase_    )




  @classmethod
  def    __lowercase       (  cls		:			Any					,A		:			Union[Path, str]					,A		:			bytes = b""    ):






   '''simple docstring'''
   if not magic_number:
    UpperCAmelCase__					:  Union[str, Any]					   =					max(len(UpperCamelCase_    ) for cls_magic_number in cls.magic_numbers    )
    try:
     UpperCAmelCase__					:  Tuple					   =					cls.read_magic_number(UpperCamelCase_					,UpperCamelCase_    )
    except OSError:
     return False
   return any(magic_number.startswith(UpperCamelCase_    ) for cls_magic_number in cls.magic_numbers    )







class      __lowercase			(    __lowerCamelCase					):

  @classmethod
  def    __lowercase       (  cls		:			Optional[int]					,A		:			Union[Path, str]					,**A		:			int    ):






   '''simple docstring'''
   return tarfile.is_tarfile(UpperCamelCase_    )

  @staticmethod
  def    __lowercase       (  A		:			Tuple					,A		:			str    ):






   '''simple docstring'''

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

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

   def badlink(A		:			Optional[int]					,A		:			str    ) -> bool:
    # Links are interpreted relative to the directory containing the link
    UpperCAmelCase__					:  Union[str, Any]					   =					resolved(os.path.join(UpperCamelCase_					,os.path.dirname(info.name    )    )    )
    return badpath(info.linkname					,base=UpperCamelCase_    )

   UpperCAmelCase__					:  Tuple					   =					resolved(UpperCamelCase_    )

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




  @staticmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			Union[Path, str]    ):






   '''simple docstring'''
   os.makedirs(UpperCamelCase_					,exist_ok=UpperCamelCase_    )
   UpperCAmelCase__					:  Optional[Any]					   =					tarfile.open(UpperCamelCase_    )
   tar_file.extractall(UpperCamelCase_					,members=TarExtractor.safemembers(UpperCamelCase_					,UpperCamelCase_    )    )
   tar_file.close()







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       [b'\x1F\x8B']

  @staticmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			Union[Path, str]    ):






   '''simple docstring'''
   with gzip.open(UpperCamelCase_					,"""rb"""    ) as gzip_file:
    with open(UpperCamelCase_					,"""wb"""    ) as extracted_file:
     shutil.copyfileobj(UpperCamelCase_					,UpperCamelCase_    )







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       [
      b'PK\x03\x04',
      b'PK\x05\x06',  # empty archive
      b'PK\x07\x08',  # spanned archive
  ]

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






   '''simple docstring'''
   if super().is_extractable(UpperCamelCase_					,magic_number=UpperCamelCase_    ):
    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(UpperCamelCase_					,"""rb"""    ) as fp:
     UpperCAmelCase__					:  Any					   =					_EndRecData(UpperCamelCase_    )
     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__					:  List[Any]					   =					fp.read(UpperCamelCase_    )  # CD is where we expect it to be
        if len(UpperCamelCase_    ) == sizeCentralDir:
         UpperCAmelCase__					:  int					   =					struct.unpack(UpperCamelCase_					,UpperCamelCase_    )  # 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    __lowercase       (  A		:			Union[Path, str]					,A		:			Union[Path, str]    ):






   '''simple docstring'''
   os.makedirs(UpperCamelCase_					,exist_ok=UpperCamelCase_    )
   with zipfile.ZipFile(UpperCamelCase_					,"""r"""    ) as zip_file:
    zip_file.extractall(UpperCamelCase_    )
    zip_file.close()







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       [b'\xFD\x37\x7A\x58\x5A\x00']

  @staticmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			Union[Path, str]    ):






   '''simple docstring'''
   with lzma.open(UpperCamelCase_    ) as compressed_file:
    with open(UpperCamelCase_					,"""wb"""    ) as extracted_file:
     shutil.copyfileobj(UpperCamelCase_					,UpperCamelCase_    )







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       [b'Rar!\x1a\x07\x00', b'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID

  @staticmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			Union[Path, str]    ):






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

   os.makedirs(UpperCamelCase_					,exist_ok=UpperCamelCase_    )
   UpperCAmelCase__					:  Any					   =					rarfile.RarFile(UpperCamelCase_    )
   rf.extractall(UpperCamelCase_    )
   rf.close()







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       [b'\x28\xb5\x2F\xFD']

  @staticmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			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(UpperCamelCase_					,"""rb"""    ) as ifh, open(UpperCamelCase_					,"""wb"""    ) as ofh:
    dctx.copy_stream(UpperCamelCase_					,UpperCamelCase_    )







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       [b'\x42\x5A\x68']

  @staticmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			Union[Path, str]    ):






   '''simple docstring'''
   with bza.open(UpperCamelCase_					,"""rb"""    ) as compressed_file:
    with open(UpperCamelCase_					,"""wb"""    ) as extracted_file:
     shutil.copyfileobj(UpperCamelCase_					,UpperCamelCase_    )







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       [b'\x37\x7A\xBC\xAF\x27\x1C']

  @staticmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			Union[Path, str]    ):






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

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







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       [b'\x04\x22\x4D\x18']

  @staticmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			Union[Path, str]    ):






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

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







class      __lowercase			:
  #  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
  snake_case_				       =       {
      "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    __lowercase       (  cls		:			Union[str, Any]    ):






   '''simple docstring'''
   return max(
       len(UpperCamelCase_    )
       for extractor in cls.extractors.values()
       if issubclass(UpperCamelCase_					,UpperCamelCase_    )
       for extractor_magic_number in extractor.magic_numbers    )

  @staticmethod
  def    __lowercase       (  A		:			Union[Path, str]					,A		:			int    ):






   '''simple docstring'''
   try:
    return MagicNumberBaseExtractor.read_magic_number(UpperCamelCase_					,magic_number_length=UpperCamelCase_    )
   except OSError:
    return b""

  @classmethod
  def    __lowercase       (  cls		:			List[Any]					,A		:			Union[Path, str]					,A		:			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=UpperCamelCase_					,)
   UpperCAmelCase__					:  Dict					   =					cls.infer_extractor_format(UpperCamelCase_    )
   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    __lowercase       (  cls		:			List[Any]					,A		:			Union[Path, str]    ):  # <Added version="2.4.0"/>






   '''simple docstring'''
   UpperCAmelCase__					:  Optional[int]					   =					cls._get_magic_number_max_length()
   UpperCAmelCase__					:  Dict					   =					cls._read_magic_number(UpperCamelCase_					,UpperCamelCase_    )
   for extractor_format, extractor in cls.extractors.items():
    if extractor.is_extractable(UpperCamelCase_					,magic_number=UpperCamelCase_    ):
     return extractor_format




  @classmethod
  def    __lowercase       (  cls		:			Tuple					,A		:			Union[Path, str]					,A		:			Union[Path, str]					,A		:			Optional[str] = None					,A		:			Optional[BaseExtractor] = "deprecated"					,):






   '''simple docstring'''
   os.makedirs(os.path.dirname(UpperCamelCase_    )					,exist_ok=UpperCamelCase_    )
   # Prevent parallel extractions
   UpperCAmelCase__					:  Dict					   =					str(Path(UpperCamelCase_    ).with_suffix(""".lock"""    )    )
   with FileLock(UpperCamelCase_    ):
    shutil.rmtree(UpperCamelCase_					,ignore_errors=UpperCamelCase_    )
    if extractor_format or extractor != "deprecated":
     if extractor != "deprecated" or not isinstance(UpperCamelCase_					,UpperCamelCase_    ):  # 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=UpperCamelCase_					,)
      UpperCAmelCase__					:  int					   =					extractor if extractor != """deprecated""" else extractor_format
     else:
      UpperCAmelCase__					:  List[str]					   =					cls.extractors[extractor_format]
     return extractor.extract(UpperCamelCase_					,UpperCamelCase_    )
    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=UpperCamelCase_					,)
     for extractor in cls.extractors.values():
      if extractor.is_extractable(UpperCamelCase_    ):
       return extractor.extract(UpperCamelCase_					,UpperCamelCase_    )








"""simple docstring"""




from ...configuration_utils import PretrainedConfig
from ...utils import logging


__UpperCAmelCase =				logging.get_logger(__name__)







class      __lowercase			(    __lowerCamelCase					):
  snake_case_				       =       """timm_backbone"""

  def __init__(  self		:			List[str]					,A		:			Any=None					,A		:			List[Any]=3					,A		:			Any=True					,A		:			Union[str, Any]=True					,A		:			List[Any]=None					,**A		:			Optional[int]					,):






   '''simple docstring'''
   super().__init__(**A    )
   UpperCAmelCase__					:  Optional[int]					   =					backbone
   UpperCAmelCase__					:  Dict					   =					num_channels
   UpperCAmelCase__					:  Optional[int]					   =					features_only
   UpperCAmelCase__					:  Tuple					   =					use_pretrained_backbone
   UpperCAmelCase__					:  str					   =					True
   UpperCAmelCase__					:  List[str]					   =					out_indices if out_indices is not None else (-1,)





