




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


lowerCamelCase__ :   Optional[Any]					=							get_logger(__name__)





class        lowerCamelCase_							:


 '''simple docstring'''







 def __init__(							self  :		Any				,				_lowerCAmelCase  :		List[Any] = None						):
       SCREAMING_SNAKE_CASE_							=			(
           os.path.join(lowerCAmelCase__				,				config.EXTRACTED_DATASETS_DIR						) if cache_dir else config.EXTRACTED_DATASETS_PATH
       )
       SCREAMING_SNAKE_CASE_							=			Extractor



 def       lowerCAmelCase_  (							self  :		Tuple				,				_lowerCAmelCase  :		Union[str, Any]						):
       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_							=			os.path.abspath(lowerCAmelCase__						)
       return os.path.join(self.extract_dir				,				hash_url_to_filename(lowerCAmelCase__						)						)



 def       lowerCAmelCase_  (							self  :		str				,				_lowerCAmelCase  :		Dict				,				_lowerCAmelCase  :		Dict						):
       return force_extract or (
           not os.path.isfile(lowerCAmelCase__						) and not (os.path.isdir(lowerCAmelCase__						) and os.listdir(lowerCAmelCase__						))
       )




 def       lowerCAmelCase_  (							self  :		int				,				_lowerCAmelCase  :		List[Any]				,				_lowerCAmelCase  :		Dict = False						):
       SCREAMING_SNAKE_CASE_							=			self.extractor.infer_extractor_format(lowerCAmelCase__						)
       if not extractor_format:
             return input_path
       SCREAMING_SNAKE_CASE_							=			self._get_output_path(lowerCAmelCase__						)
       if self._do_extract(lowerCAmelCase__				,				lowerCAmelCase__						):
             self.extractor.extract(lowerCAmelCase__				,				lowerCAmelCase__				,				lowerCAmelCase__						)
       return output_path





class        lowerCamelCase_							(      __UpperCamelCase					):


 '''simple docstring'''







 @classmethod
 @abstractmethod
 def       lowerCAmelCase_  (							cls  :		Dict				,				_lowerCAmelCase  :		Union[str, Any]				,				**_lowerCAmelCase  :		List[str]						):
       ...




 @staticmethod
 @abstractmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		Tuple				,				_lowerCAmelCase  :		Optional[int]						):
       ...





class        lowerCamelCase_							(      __UpperCamelCase       ,   __UpperCamelCase					):


 '''simple docstring'''







 lowercase_				    =    []



 @staticmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		Tuple				,				_lowerCAmelCase  :		List[Any]						):
       with open(lowerCAmelCase__				,				'rb'						) as f:
             return f.read(lowerCAmelCase__						)




 @classmethod
 def       lowerCAmelCase_  (							cls  :		Optional[int]				,				_lowerCAmelCase  :		Optional[int]				,				_lowerCAmelCase  :		List[Any] = b""						):
       if not magic_number:
             SCREAMING_SNAKE_CASE_							=			max(len(lowerCAmelCase__						) for cls_magic_number in cls.magic_numbers						)
             try:
                   SCREAMING_SNAKE_CASE_							=			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        lowerCamelCase_							(      __UpperCamelCase					):


 '''simple docstring'''







 @classmethod
 def       lowerCAmelCase_  (							cls  :		List[Any]				,				_lowerCAmelCase  :		Any				,				**_lowerCAmelCase  :		int						):
       return tarfile.is_tarfile(lowerCAmelCase__						)



 @staticmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		Dict				,				_lowerCAmelCase  :		str						):

       def resolved(_lowerCAmelCase  :		int						) -> str:
             return os.path.realpath(os.path.abspath(lowerCAmelCase__						)						)

       def badpath(_lowerCAmelCase  :		List[Any]				,				_lowerCAmelCase  :		Union[str, Any]						) -> bool:
             # joinpath will ignore base if path is absolute
             return not resolved(os.path.join(lowerCAmelCase__				,				lowerCAmelCase__						)						).startswith(lowerCAmelCase__						)

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

       SCREAMING_SNAKE_CASE_							=			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  :		str				,				_lowerCAmelCase  :		int						):
       os.makedirs(lowerCAmelCase__				,				exist_ok=lowerCAmelCase__						)
       SCREAMING_SNAKE_CASE_							=			tarfile.open(lowerCAmelCase__						)
       tar_file.extractall(lowerCAmelCase__				,				members=TarExtractor.safemembers(lowerCAmelCase__				,				lowerCAmelCase__						)						)
       tar_file.close()





class        lowerCamelCase_							(      __UpperCamelCase					):


 '''simple docstring'''







 lowercase_				    =    [b'\x1F\x8B']



 @staticmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		Any				,				_lowerCAmelCase  :		Union[str, Any]						):
       with gzip.open(lowerCAmelCase__				,				'rb'						) as gzip_file:
             with open(lowerCAmelCase__				,				'wb'						) as extracted_file:
                   shutil.copyfileobj(lowerCAmelCase__				,				lowerCAmelCase__						)





class        lowerCamelCase_							(      __UpperCamelCase					):


 '''simple docstring'''







 lowercase_				    =    [
     b'PK\x03\x04',
     b'PK\x05\x06',  # empty archive
     b'PK\x07\x08',  # spanned archive
 ]



 @classmethod
 def       lowerCAmelCase_  (							cls  :		Optional[Any]				,				_lowerCAmelCase  :		List[str]				,				_lowerCAmelCase  :		Optional[Any] = b""						):
       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_							=			_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_							=			fp.read(lowerCAmelCase__						)  # CD is where we expect it to be
                                     if len(lowerCAmelCase__						) == sizeCentralDir:
                                           SCREAMING_SNAKE_CASE_							=			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[str, Any]				,				_lowerCAmelCase  :		List[str]						):
       os.makedirs(lowerCAmelCase__				,				exist_ok=lowerCAmelCase__						)
       with zipfile.ZipFile(lowerCAmelCase__				,				'r'						) as zip_file:
             zip_file.extractall(lowerCAmelCase__						)
             zip_file.close()





class        lowerCamelCase_							(      __UpperCamelCase					):


 '''simple docstring'''







 lowercase_				    =    [b'\xFD\x37\x7A\x58\x5A\x00']



 @staticmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		int				,				_lowerCAmelCase  :		Optional[int]						):
       with lzma.open(lowerCAmelCase__						) as compressed_file:
             with open(lowerCAmelCase__				,				'wb'						) as extracted_file:
                   shutil.copyfileobj(lowerCAmelCase__				,				lowerCAmelCase__						)





class        lowerCamelCase_							(      __UpperCamelCase					):


 '''simple docstring'''







 lowercase_				    =    [b'Rar!\x1a\x07\x00', b'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID



 @staticmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		str				,				_lowerCAmelCase  :		List[Any]						):
       if not config.RARFILE_AVAILABLE:
             raise ImportError('Please pip install rarfile'						)
       import rarfile

       os.makedirs(lowerCAmelCase__				,				exist_ok=lowerCAmelCase__						)
       SCREAMING_SNAKE_CASE_							=			rarfile.RarFile(lowerCAmelCase__						)
       rf.extractall(lowerCAmelCase__						)
       rf.close()





class        lowerCamelCase_							(      __UpperCamelCase					):


 '''simple docstring'''







 lowercase_				    =    [b'\x28\xb5\x2F\xFD']



 @staticmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		List[Any]				,				_lowerCAmelCase  :		Tuple						):
       if not config.ZSTANDARD_AVAILABLE:
             raise ImportError('Please pip install zstandard'						)
       import zstandard as zstd

       SCREAMING_SNAKE_CASE_							=			zstd.ZstdDecompressor()
       with open(lowerCAmelCase__				,				'rb'						) as ifh, open(lowerCAmelCase__				,				'wb'						) as ofh:
             dctx.copy_stream(lowerCAmelCase__				,				lowerCAmelCase__						)





class        lowerCamelCase_							(      __UpperCamelCase					):


 '''simple docstring'''







 lowercase_				    =    [b'\x42\x5A\x68']



 @staticmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		Tuple				,				_lowerCAmelCase  :		Any						):
       with bza.open(lowerCAmelCase__				,				'rb'						) as compressed_file:
             with open(lowerCAmelCase__				,				'wb'						) as extracted_file:
                   shutil.copyfileobj(lowerCAmelCase__				,				lowerCAmelCase__						)





class        lowerCamelCase_							(      __UpperCamelCase					):


 '''simple docstring'''







 lowercase_				    =    [b'\x37\x7A\xBC\xAF\x27\x1C']



 @staticmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		List[Any]				,				_lowerCAmelCase  :		List[str]						):
       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        lowerCamelCase_							(      __UpperCamelCase					):


 '''simple docstring'''







 lowercase_				    =    [b'\x04\x22\x4D\x18']



 @staticmethod
 def       lowerCAmelCase_  (							_lowerCAmelCase  :		Optional[int]				,				_lowerCAmelCase  :		Dict						):
       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        lowerCamelCase_							:


 '''simple docstring'''







 lowercase_				    =    {
     "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  :		Dict						):
       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  :		List[Any]				,				_lowerCAmelCase  :		Optional[int]						):
       try:
             return MagicNumberBaseExtractor.read_magic_number(lowerCAmelCase__				,				magic_number_length=lowerCAmelCase__						)
       except OSError:
             return b""



 @classmethod
 def       lowerCAmelCase_  (							cls  :		Tuple				,				_lowerCAmelCase  :		List[str]				,				_lowerCAmelCase  :		Any = False						):
       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_							=			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  :		Dict				,				_lowerCAmelCase  :		Tuple						):  # <Added version="2.4.0"/>
       SCREAMING_SNAKE_CASE_							=			cls._get_magic_number_max_length()
       SCREAMING_SNAKE_CASE_							=			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[str, Any]				,				_lowerCAmelCase  :		List[str]				,				_lowerCAmelCase  :		List[Any] = None				,				_lowerCAmelCase  :		List[Any] = "deprecated"				,				):
       os.makedirs(os.path.dirname(lowerCAmelCase__						)				,				exist_ok=lowerCAmelCase__						)
       # Prevent parallel extractions
       SCREAMING_SNAKE_CASE_							=			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_							=			extractor if extractor != 'deprecated' else extractor_format
                   else:
                         SCREAMING_SNAKE_CASE_							=			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__						)



def    snake_case_     (  snake_case			,							snake_case     )  ->				bool:
       return numa ^ numa < 0


if __name__ == "__main__":
 import doctest

 doctest.testmod()


