


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


SCREAMING_SNAKE_CASE :    Tuple									=				get_logger(__name__)



class 			_UpperCAmelCase :






		'''simple docstring'''

		def __init__(self				,       a_ = None					):





			'''simple docstring'''

			__snake_case	:						Optional[int]						=				(
			    os.path.join(a_				,       config.EXTRACTED_DATASETS_DIR					) if cache_dir else config.EXTRACTED_DATASETS_PATH
			)
			__snake_case	:						List[Any]						=				Extractor



		def 				SCREAMING_SNAKE_CASE  (self				,       a_					):





			'''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"
			__snake_case	:						Union[str, Any]						=				os.path.abspath(a_					)
			return os.path.join(self.extract_dir				,       hash_url_to_filename(a_					)					)



		def 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_					):





			'''simple docstring'''

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



		def 				SCREAMING_SNAKE_CASE  (self				,       a_				,       a_ = False					):





			'''simple docstring'''

			__snake_case	:						Tuple						=				self.extractor.infer_extractor_format(a_					)
			if not extractor_format:
				return input_path
			__snake_case	:						Union[str, Any]						=				self._get_output_path(a_					)
			if self._do_extract(a_				,       a_					):
				self.extractor.extract(a_				,       a_				,       a_					)
			return output_path



class 			_UpperCAmelCase (							lowercase_				):






		'''simple docstring'''

		@classmethod
		@abstractmethod
		def 				SCREAMING_SNAKE_CASE  (cls				,       a_				,       **a_					):





			'''simple docstring'''

			...



		@staticmethod
		@abstractmethod
		def 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

			...



class 			_UpperCAmelCase (							lowercase_,				lowercase_				):






		'''simple docstring'''

		lowerCamelCase__				=[]



		@staticmethod
		def 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

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



		@classmethod
		def 				SCREAMING_SNAKE_CASE  (cls				,       a_				,       a_ = b""					):





			'''simple docstring'''

			if not magic_number:
				__snake_case	:						Optional[Any]						=				max(len(a_					) for cls_magic_number in cls.magic_numbers					)
				try:
					__snake_case	:						int						=				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 			_UpperCAmelCase (							lowercase_				):






		'''simple docstring'''

		@classmethod
		def 				SCREAMING_SNAKE_CASE  (cls				,       a_				,       **a_					):





			'''simple docstring'''

			return tarfile.is_tarfile(a_					)



		@staticmethod
		def 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

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

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

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

			__snake_case	:						List[Any]						=				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 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

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



class 			_UpperCAmelCase (							lowercase_				):






		'''simple docstring'''

		lowerCamelCase__				=[B"""\x1F\x8B"""]



		@staticmethod
		def 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

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



class 			_UpperCAmelCase (							lowercase_				):






		'''simple docstring'''

		lowerCamelCase__				=[
		    B"""PK\x03\x04""",
		    B"""PK\x05\x06""",  # empty archive
		    B"""PK\x07\x08""",  # spanned archive
		]



		@classmethod
		def 				SCREAMING_SNAKE_CASE  (cls				,       a_				,       a_ = 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:
					__snake_case	:						Optional[Any]						=				_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:
								__snake_case	:						Union[str, Any]						=				fp.read(a_					)  # CD is where we expect it to be
								if len(a_					) == sizeCentralDir:
									__snake_case	:						List[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 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

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



class 			_UpperCAmelCase (							lowercase_				):






		'''simple docstring'''

		lowerCamelCase__				=[B"""\xFD\x37\x7A\x58\x5A\x00"""]



		@staticmethod
		def 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

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



class 			_UpperCAmelCase (							lowercase_				):






		'''simple docstring'''

		lowerCamelCase__				=[B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID



		@staticmethod
		def 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

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

			os.makedirs(a_				,       exist_ok=a_					)
			__snake_case	:						Optional[int]						=				rarfile.RarFile(a_					)
			rf.extractall(a_					)
			rf.close()



class 			_UpperCAmelCase (							lowercase_				):






		'''simple docstring'''

		lowerCamelCase__				=[B"""\x28\xb5\x2F\xFD"""]



		@staticmethod
		def 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

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

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



class 			_UpperCAmelCase (							lowercase_				):






		'''simple docstring'''

		lowerCamelCase__				=[B"""\x42\x5A\x68"""]



		@staticmethod
		def 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

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



class 			_UpperCAmelCase (							lowercase_				):






		'''simple docstring'''

		lowerCamelCase__				=[B"""\x37\x7A\xBC\xAF\x27\x1C"""]



		@staticmethod
		def 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''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 			_UpperCAmelCase (							lowercase_				):






		'''simple docstring'''

		lowerCamelCase__				=[B"""\x04\x22\x4D\x18"""]



		@staticmethod
		def 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''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 			_UpperCAmelCase :






		'''simple docstring'''

		lowerCamelCase__				={
		    "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 				SCREAMING_SNAKE_CASE  (cls					):





			'''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 				SCREAMING_SNAKE_CASE  (a_				,       a_					):





			'''simple docstring'''

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



		@classmethod
		def 				SCREAMING_SNAKE_CASE  (cls				,       a_				,       a_ = 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_				,       )
			__snake_case	:						str						=				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 				SCREAMING_SNAKE_CASE  (cls				,       a_					):  # <Added version="2.4.0"/>





			'''simple docstring'''

			__snake_case	:						Any						=				cls._get_magic_number_max_length()
			__snake_case	:						Optional[Any]						=				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 				SCREAMING_SNAKE_CASE  (cls				,       a_				,       a_				,       a_ = None				,       a_ = "deprecated"				,       ):





			'''simple docstring'''

			os.makedirs(os.path.dirname(a_					)				,       exist_ok=a_					)
			# Prevent parallel extractions
			__snake_case	:						List[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_				,       )
						__snake_case	:						Any						=				extractor if extractor != '''deprecated''' else extractor_format
					else:
						__snake_case	:						Dict						=				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'''

def _SCREAMING_SNAKE_CASE      (A       )       ->       int:






       """simple docstring"""







       if not isinstance(A  , A       ):
              raise TypeError('''only integers accepted as input'''       )
       else:
              lowercase__      			= str(abs(A       )       )
              lowercase__      			= [list(A       ) for char in range(len(A       )       )]
              for index in range(len(A       )       ):
                     num_transpositions[index].pop(A       )
              return max(
                  int(''''''.join(list(A       )       )       ) for transposition in num_transpositions       )


if __name__ == "__main__":
 __import__('doctest').testmod()




