






'''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__						:Optional[Any]          =			get_logger(__name__)







class 	SCREAMING_SNAKE_CASE	:




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


            """simple docstring"""







            __lowerCamelCase						:       Optional[int]				   =				(
                os.path.join(A__	,    config.EXTRACTED_DATASETS_DIR					) if cache_dir else config.EXTRACTED_DATASETS_PATH
            )
            __lowerCamelCase						:       Union[str, Any]				   =				Extractor




       def 					a_					(					self      : Tuple	,    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"
            __lowerCamelCase						:       Optional[int]				   =				os.path.abspath(A__					)
            return os.path.join(self.extract_dir	,    hash_url_to_filename(A__					)					)




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


            """simple docstring"""







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




       def 					a_					(					self      : int	,    A__      : str	,    A__      : bool = False					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[int]				   =				self.extractor.infer_extractor_format(A__					)
            if not extractor_format:
                 return input_path
            __lowerCamelCase						:       Union[str, Any]				   =				self._get_output_path(A__					)
            if self._do_extract(A__	,    A__					):
                 self.extractor.extract(A__	,    A__	,    A__					)
            return output_path







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):




       @classmethod
       @abstractmethod
       def 					a_					(					cls      : List[Any]	,    A__      : Union[Path, str]	,    **A__      : Dict					):


            """simple docstring"""







            ...




       @staticmethod
       @abstractmethod
       def 					a_					(					A__      : Union[Path, str]	,    A__      : Union[Path, str]					):


            """simple docstring"""







            ...







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_    ,   lowerCAmelCase_  ):
       snake_case__    :     List[bytes]   		=			[]




       @staticmethod
       def 					a_					(					A__      : Union[Path, str]	,    A__      : int					):


            """simple docstring"""







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




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


            """simple docstring"""







            if not magic_number:
                 __lowerCamelCase						:       Optional[int]				   =				max(len(A__					) for cls_magic_number in cls.magic_numbers					)
                 try:
                      __lowerCamelCase						:       Dict				   =				cls.read_magic_number(A__	,    A__					)
                 except OSError:
                      return False
            return any(magic_number.startswith(A__					) for cls_magic_number in cls.magic_numbers					)







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):




       @classmethod
       def 					a_					(					cls      : Dict	,    A__      : Union[Path, str]	,    **A__      : Union[str, Any]					):


            """simple docstring"""







            return tarfile.is_tarfile(A__					)




       @staticmethod
       def 					a_					(					A__      : Optional[int]	,    A__      : List[Any]					):


            """simple docstring"""







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

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

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

            __lowerCamelCase						:       Tuple				   =				resolved(A__					)

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




       @staticmethod
       def 					a_					(					A__      : Union[Path, str]	,    A__      : Union[Path, str]					):


            """simple docstring"""







            os.makedirs(A__	,    exist_ok=A__					)
            __lowerCamelCase						:       int				   =				tarfile.open(A__					)
            tar_file.extractall(A__	,    members=TarExtractor.safemembers(A__	,    A__					)					)
            tar_file.close()







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     Optional[Any]   		=			[B'\x1F\x8B']




       @staticmethod
       def 					a_					(					A__      : Union[Path, str]	,    A__      : Union[Path, str]					):


            """simple docstring"""







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







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     int   		=			[
           B'PK\x03\x04',
           B'PK\x05\x06',  # empty archive
           B'PK\x07\x08',  # spanned archive
       ]




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


            """simple docstring"""







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


            """simple docstring"""







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







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     Union[str, Any]   		=			[B'\xFD\x37\x7A\x58\x5A\x00']




       @staticmethod
       def 					a_					(					A__      : Union[Path, str]	,    A__      : Union[Path, str]					):


            """simple docstring"""







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







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     Dict   		=			[B'Rar!\x1a\x07\x00', B'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID




       @staticmethod
       def 					a_					(					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(A__	,    exist_ok=A__					)
            __lowerCamelCase						:       int				   =				rarfile.RarFile(A__					)
            rf.extractall(A__					)
            rf.close()







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     int   		=			[B'\x28\xb5\x2F\xFD']




       @staticmethod
       def 					a_					(					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

            __lowerCamelCase						:       str				   =				zstd.ZstdDecompressor()
            with open(A__	,    """rb"""					) as ifh, open(A__	,    """wb"""					) as ofh:
                 dctx.copy_stream(A__	,    A__					)







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     int   		=			[B'\x42\x5A\x68']




       @staticmethod
       def 					a_					(					A__      : Union[Path, str]	,    A__      : Union[Path, str]					):


            """simple docstring"""







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







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     List[str]   		=			[B'\x37\x7A\xBC\xAF\x27\x1C']




       @staticmethod
       def 					a_					(					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(A__	,    exist_ok=A__					)
            with pyazr.SevenZipFile(A__	,    """r"""					) as archive:
                 archive.extractall(A__					)







class 	SCREAMING_SNAKE_CASE	(      lowerCAmelCase_  ):
       snake_case__    :     str   		=			[B'\x04\x22\x4D\x18']




       @staticmethod
       def 					a_					(					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(A__	,    """rb"""					) as compressed_file:
                 with open(A__	,    """wb"""					) as extracted_file:
                      shutil.copyfileobj(A__	,    A__					)







class 	SCREAMING_SNAKE_CASE	:
       #  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__    :     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 					a_					(					cls      : Union[str, Any]					):


            """simple docstring"""







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




       @staticmethod
       def 					a_					(					A__      : Union[Path, str]	,    A__      : int					):


            """simple docstring"""







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




       @classmethod
       def 					a_					(					cls      : List[str]	,    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=A__	,    )
            __lowerCamelCase						:       Union[str, Any]				   =				cls.infer_extractor_format(A__					)
            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 					a_					(					cls      : int	,    A__      : Union[Path, str]					):  # <Added version="2.4.0"/>


            """simple docstring"""







            __lowerCamelCase						:       int				   =				cls._get_magic_number_max_length()
            __lowerCamelCase						:       List[str]				   =				cls._read_magic_number(A__	,    A__					)
            for extractor_format, extractor in cls.extractors.items():
                 if extractor.is_extractable(A__	,    magic_number=A__					):
                      return extractor_format




       @classmethod
       def 					a_					(					cls      : Union[str, Any]	,    A__      : Union[Path, str]	,    A__      : Union[Path, str]	,    A__      : Optional[str] = None	,    A__      : Optional[BaseExtractor] = "deprecated"	,    ):


            """simple docstring"""







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











'''simple docstring'''

from ..utils import DummyObject, requires_backends







class 	SCREAMING_SNAKE_CASE	(      metaclass=lowerCAmelCase_  ):
       snake_case__    :     Union[str, Any]   		=			['torch', 'torchsde']




       def __init__(					self      : int	,    *A__      : Optional[Any]	,    **A__      : Dict					):


            """simple docstring"""







            requires_backends(self	,    ["""torch""", """torchsde"""]					)




       @classmethod
       def 					a_					(					cls      : Optional[Any]	,    *A__      : str	,    **A__      : Optional[Any]					):


            """simple docstring"""







            requires_backends(cls	,    ["""torch""", """torchsde"""]					)




       @classmethod
       def 					a_					(					cls      : Union[str, Any]	,    *A__      : Any	,    **A__      : Union[str, Any]					):


            """simple docstring"""







            requires_backends(cls	,    ["""torch""", """torchsde"""]					)



