



"""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 					a	:



  def __init__(						self :					Union[str, Any]       ,		lowerCAmelCase :					Optional[str] = None		)     ->					Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Any     			=(
         os.path.join(lowerCAmelCase       ,		config.EXTRACTED_DATASETS_DIR		) if cache_dir else config.EXTRACTED_DATASETS_PATH
     )
     SCREAMING_SNAKE_CASE_: Dict     			=Extractor



  def 	lowerCamelCase__       (						self :					int       ,		lowerCAmelCase :					str		)     ->					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"
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=os.path.abspath(lowerCAmelCase		)
     return os.path.join(self.extract_dir       ,		hash_url_to_filename(lowerCAmelCase		)		)



  def 	lowerCamelCase__       (						self :					List[Any]       ,		lowerCAmelCase :					str       ,		lowerCAmelCase :					bool		)     ->					bool:


     '''simple docstring'''




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





  def 	lowerCamelCase__       (						self :					List[str]       ,		lowerCAmelCase :					str       ,		lowerCAmelCase :					bool = False		)     ->					str:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Optional[int]     			=self.extractor.infer_extractor_format(lowerCAmelCase		)
     if not extractor_format:
        return input_path
     SCREAMING_SNAKE_CASE_: int     			=self._get_output_path(lowerCAmelCase		)
     if self._do_extract(lowerCAmelCase       ,		lowerCAmelCase		):
        self.extractor.extract(lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase		)
     return output_path







class 					a	(  UpperCAmelCase__       ):



  @classmethod
  @abstractmethod
  def 	lowerCamelCase__       (						cls :					Any       ,		lowerCAmelCase :					Union[Path, str]       ,		**lowerCAmelCase :					List[Any]		)     ->					bool:


     '''simple docstring'''




     ...





  @staticmethod
  @abstractmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Union[Path, str]		)     ->					None:


     '''simple docstring'''




     ...







class 					a	(  UpperCAmelCase__	,      UpperCAmelCase__       ):
  UpperCamelCase	:				List[bytes]     						=					[]



  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					int		)     ->					Dict:


     '''simple docstring'''




     with open(lowerCAmelCase       ,		"""rb"""		) as f:
        return f.read(lowerCAmelCase		)





  @classmethod
  def 	lowerCamelCase__       (						cls :					Tuple       ,		lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					bytes = b""		)     ->					bool:


     '''simple docstring'''




     if not magic_number:
        SCREAMING_SNAKE_CASE_: str     			=max(len(lowerCAmelCase		) for cls_magic_number in cls.magic_numbers		)
        try:
           SCREAMING_SNAKE_CASE_: Any     			=cls.read_magic_number(lowerCAmelCase       ,		lowerCAmelCase		)
        except OSError:
           return False
     return any(magic_number.startswith(lowerCAmelCase		) for cls_magic_number in cls.magic_numbers		)







class 					a	(  UpperCAmelCase__       ):



  @classmethod
  def 	lowerCamelCase__       (						cls :					str       ,		lowerCAmelCase :					Union[Path, str]       ,		**lowerCAmelCase :					Optional[Any]		)     ->					bool:


     '''simple docstring'''




     return tarfile.is_tarfile(lowerCAmelCase		)



  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Optional[Any]       ,		lowerCAmelCase :					int		)     ->					Union[str, Any]:


     '''simple docstring'''




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

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

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

     SCREAMING_SNAKE_CASE_: Dict     			=resolved(lowerCAmelCase		)

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





  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Union[Path, str]		)     ->					None:


     '''simple docstring'''




     os.makedirs(lowerCAmelCase       ,		exist_ok=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=tarfile.open(lowerCAmelCase		)
     tar_file.extractall(lowerCAmelCase       ,		members=TarExtractor.safemembers(lowerCAmelCase       ,		lowerCAmelCase		)		)
     tar_file.close()







class 					a	(  UpperCAmelCase__       ):
  UpperCamelCase	:				str     						=					[B'\x1F\x8B']



  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Union[Path, str]		)     ->					None:


     '''simple docstring'''




     with gzip.open(lowerCAmelCase       ,		"""rb"""		) as gzip_file:
        with open(lowerCAmelCase       ,		"""wb"""		) as extracted_file:
           shutil.copyfileobj(lowerCAmelCase       ,		lowerCAmelCase		)







class 					a	(  UpperCAmelCase__       ):
  UpperCamelCase	:				Dict     						=					[
      B'PK\x03\x04',
      B'PK\x05\x06',  # empty archive
      B'PK\x07\x08',  # spanned archive
  ]



  @classmethod
  def 	lowerCamelCase__       (						cls :					List[Any]       ,		lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					bytes = b""		)     ->					bool:


     '''simple docstring'''




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


     '''simple docstring'''




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







class 					a	(  UpperCAmelCase__       ):
  UpperCamelCase	:				List[Any]     						=					[B'\xFD\x37\x7A\x58\x5A\x00']



  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Union[Path, str]		)     ->					None:


     '''simple docstring'''




     with lzma.open(lowerCAmelCase		) as compressed_file:
        with open(lowerCAmelCase       ,		"""wb"""		) as extracted_file:
           shutil.copyfileobj(lowerCAmelCase       ,		lowerCAmelCase		)







class 					a	(  UpperCAmelCase__       ):
  UpperCamelCase	:				List[str]     						=					[B'Rar!\x1a\x07\x00', B'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID



  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Union[Path, str]		)     ->					None:


     '''simple docstring'''




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

     os.makedirs(lowerCAmelCase       ,		exist_ok=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Dict     			=rarfile.RarFile(lowerCAmelCase		)
     rf.extractall(lowerCAmelCase		)
     rf.close()







class 					a	(  UpperCAmelCase__       ):
  UpperCamelCase	:				List[str]     						=					[B'\x28\xb5\x2F\xFD']



  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Union[Path, str]		)     ->					None:


     '''simple docstring'''




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

     SCREAMING_SNAKE_CASE_: int     			=zstd.ZstdDecompressor()
     with open(lowerCAmelCase       ,		"""rb"""		) as ifh, open(lowerCAmelCase       ,		"""wb"""		) as ofh:
        dctx.copy_stream(lowerCAmelCase       ,		lowerCAmelCase		)







class 					a	(  UpperCAmelCase__       ):
  UpperCamelCase	:				int     						=					[B'\x42\x5A\x68']



  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Union[Path, str]		)     ->					None:


     '''simple docstring'''




     with bza.open(lowerCAmelCase       ,		"""rb"""		) as compressed_file:
        with open(lowerCAmelCase       ,		"""wb"""		) as extracted_file:
           shutil.copyfileobj(lowerCAmelCase       ,		lowerCAmelCase		)







class 					a	(  UpperCAmelCase__       ):
  UpperCamelCase	:				int     						=					[B'\x37\x7A\xBC\xAF\x27\x1C']



  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Union[Path, str]		)     ->					None:


     '''simple docstring'''




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

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







class 					a	(  UpperCAmelCase__       ):
  UpperCamelCase	:				Optional[int]     						=					[B'\x04\x22\x4D\x18']



  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Union[Path, str]		)     ->					None:


     '''simple docstring'''




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

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







class 					a	:
  #  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
  UpperCamelCase	:				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 :					List[Any]		)     ->					Optional[int]:


     '''simple docstring'''




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



  @staticmethod
  def 	lowerCamelCase__       (						lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					int		)     ->					Tuple:


     '''simple docstring'''




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



  @classmethod
  def 	lowerCamelCase__       (						cls :					str       ,		lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					bool = False		)     ->					bool:


     '''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=lowerCAmelCase       ,		)
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=cls.infer_extractor_format(lowerCAmelCase		)
     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       ,		lowerCAmelCase :					Union[Path, str]		)     ->					str:  # <Added version="2.4.0"/>


     '''simple docstring'''




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





  @classmethod
  def 	lowerCamelCase__       (						cls :					List[Any]       ,		lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Union[Path, str]       ,		lowerCAmelCase :					Optional[str] = None       ,		lowerCAmelCase :					Optional[BaseExtractor] = "deprecated"       ,		)     ->					None:


     '''simple docstring'''




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








"""simple docstring"""
import string





def      __magic_name__				(							lowercase ):
   SCREAMING_SNAKE_CASE_: List[Any]     			=""""""
   for i in sequence:
      SCREAMING_SNAKE_CASE_: List[Any]     			=ord(lowercase )
      if 65 <= extract <= 90:
         output += chr(155 - extract )
      elif 97 <= extract <= 122:
         output += chr(219 - extract )
      else:
         output += i
   return output





def      __magic_name__				(							lowercase ):
   SCREAMING_SNAKE_CASE_: Any     			=string.ascii_letters
   SCREAMING_SNAKE_CASE_: Tuple     			=string.ascii_lowercase[::-1] + string.ascii_uppercase[::-1]
   return "".join(
       letters_reversed[letters.index(lowercase )] if c in letters else c for c in sequence )





def      __magic_name__				(							):
   from timeit import timeit

   print("""Running performance benchmarks...""" )
   SCREAMING_SNAKE_CASE_: int     			="""from string import printable ; from __main__ import atbash, atbash_slow"""
   print(f'''> atbash_slow(): {timeit("atbash_slow(printable)"							,			setup=lowercase )} seconds''' )
   print(f'''>      atbash(): {timeit("atbash(printable)"							,			setup=lowercase )} seconds''' )


if __name__ == "__main__":
   for example in ("ABCDEFGH", "123GGjj", "testStringtest", "with space"):
      print(f"""{example} encrypted in atbash: {atbash(example)}""")
   benchmark()



