



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


lowerCAmelCase	:		List[Any]				=   get_logger(__name__)






class 					UpperCAmelCase__	:



     def __init__(    self			,				UpperCamelCase = None     )     ->			Union[str, Any]:
      __lowerCAmelCase												=  (
          os.path.join(UpperCamelCase			,				config.EXTRACTED_DATASETS_DIR     ) if cache_dir else config.EXTRACTED_DATASETS_PATH
      )
      __lowerCAmelCase												=  Extractor



     def        UpperCAmelCase_ (    self			,				UpperCamelCase     )     ->			str:
      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												=  os.path.abspath(UpperCamelCase     )
      return os.path.join(self.extract_dir			,				hash_url_to_filename(UpperCamelCase     )     )



     def        UpperCAmelCase_ (    self			,				UpperCamelCase			,				UpperCamelCase     )     ->			bool:
      return force_extract or (
          not os.path.isfile(UpperCamelCase     ) and not (os.path.isdir(UpperCamelCase     ) and os.listdir(UpperCamelCase     ))
      )



     def        UpperCAmelCase_ (    self			,				UpperCamelCase			,				UpperCamelCase = False     )     ->			str:
      __lowerCAmelCase												=  self.extractor.infer_extractor_format(UpperCamelCase     )
      if not extractor_format:
       return input_path
      __lowerCAmelCase												=  self._get_output_path(UpperCamelCase     )
      if self._do_extract(UpperCamelCase			,				UpperCamelCase     ):
       self.extractor.extract(UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase     )
      return output_path






class 					UpperCAmelCase__	(		UpperCamelCase__ ):



     @classmethod
     @abstractmethod
     def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				**UpperCamelCase     )     ->			bool:
      ...



     @staticmethod
     @abstractmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
      ...






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



     @staticmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			List[Any]:
      with open(UpperCamelCase			,				"rb"     ) as f:
       return f.read(UpperCamelCase     )



     @classmethod
     def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				UpperCamelCase = b""     )     ->			bool:
      if not magic_number:
       __lowerCAmelCase												=  max(len(UpperCamelCase     ) for cls_magic_number in cls.magic_numbers     )
       try:
        __lowerCAmelCase												=  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 					UpperCAmelCase__	(		UpperCamelCase__ ):



     @classmethod
     def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				**UpperCamelCase     )     ->			bool:
      return tarfile.is_tarfile(UpperCamelCase     )



     @staticmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			Dict:

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

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

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

      __lowerCAmelCase												=  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        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
      os.makedirs(UpperCamelCase			,				exist_ok=UpperCamelCase     )
      __lowerCAmelCase												=  tarfile.open(UpperCamelCase     )
      tar_file.extractall(UpperCamelCase			,				members=TarExtractor.safemembers(UpperCamelCase			,				UpperCamelCase     )     )
      tar_file.close()






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
     a      :     Any        =							[B"""\x1F\x8B"""]



     @staticmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
      with gzip.open(UpperCamelCase			,				"rb"     ) as gzip_file:
       with open(UpperCamelCase			,				"wb"     ) as extracted_file:
        shutil.copyfileobj(UpperCamelCase			,				UpperCamelCase     )






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
     a      :     List[Any]        =							[
         B"""PK\x03\x04""",
         B"""PK\x05\x06""",  # empty archive
         B"""PK\x07\x08""",  # spanned archive
     ]



     @classmethod
     def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				UpperCamelCase = b""     )     ->			bool:
      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:
        __lowerCAmelCase												=  _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:
           __lowerCAmelCase												=  fp.read(UpperCamelCase     )  # CD is where we expect it to be
           if len(UpperCamelCase     ) == sizeCentralDir:
            __lowerCAmelCase												=  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        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
      os.makedirs(UpperCamelCase			,				exist_ok=UpperCamelCase     )
      with zipfile.ZipFile(UpperCamelCase			,				"r"     ) as zip_file:
       zip_file.extractall(UpperCamelCase     )
       zip_file.close()






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
     a      :     Tuple        =							[B"""\xFD\x37\x7A\x58\x5A\x00"""]



     @staticmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
      with lzma.open(UpperCamelCase     ) as compressed_file:
       with open(UpperCamelCase			,				"wb"     ) as extracted_file:
        shutil.copyfileobj(UpperCamelCase			,				UpperCamelCase     )






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



     @staticmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
      if not config.RARFILE_AVAILABLE:
       raise ImportError("Please pip install rarfile"     )
      import rarfile

      os.makedirs(UpperCamelCase			,				exist_ok=UpperCamelCase     )
      __lowerCAmelCase												=  rarfile.RarFile(UpperCamelCase     )
      rf.extractall(UpperCamelCase     )
      rf.close()






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
     a      :     int        =							[B"""\x28\xb5\x2F\xFD"""]



     @staticmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
      if not config.ZSTANDARD_AVAILABLE:
       raise ImportError("Please pip install zstandard"     )
      import zstandard as zstd

      __lowerCAmelCase												=  zstd.ZstdDecompressor()
      with open(UpperCamelCase			,				"rb"     ) as ifh, open(UpperCamelCase			,				"wb"     ) as ofh:
       dctx.copy_stream(UpperCamelCase			,				UpperCamelCase     )






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
     a      :     Any        =							[B"""\x42\x5A\x68"""]



     @staticmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
      with bza.open(UpperCamelCase			,				"rb"     ) as compressed_file:
       with open(UpperCamelCase			,				"wb"     ) as extracted_file:
        shutil.copyfileobj(UpperCamelCase			,				UpperCamelCase     )






class 					UpperCAmelCase__	(		UpperCamelCase__ ):
     a      :     Any        =							[B"""\x37\x7A\xBC\xAF\x27\x1C"""]



     @staticmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
      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 					UpperCAmelCase__	(		UpperCamelCase__ ):
     a      :     Any        =							[B"""\x04\x22\x4D\x18"""]



     @staticmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			None:
      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 					UpperCAmelCase__	:
     #  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
     a      :     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        UpperCAmelCase_ (    cls     )     ->			Optional[Any]:
      return max(
          len(UpperCamelCase     )
          for extractor in cls.extractors.values()
          if issubclass(UpperCamelCase			,				UpperCamelCase     )
          for extractor_magic_number in extractor.magic_numbers     )



     @staticmethod
     def        UpperCAmelCase_ (    UpperCamelCase			,				UpperCamelCase     )     ->			Dict:
      try:
       return MagicNumberBaseExtractor.read_magic_number(UpperCamelCase			,				magic_number_length=UpperCamelCase     )
      except OSError:
       return b""



     @classmethod
     def        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				UpperCamelCase = False     )     ->			bool:
      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			,				)
      __lowerCAmelCase												=  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        UpperCAmelCase_ (    cls			,				UpperCamelCase     )     ->			str:  # <Added version="2.4.0"/>
      __lowerCAmelCase												=  cls._get_magic_number_max_length()
      __lowerCAmelCase												=  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        UpperCAmelCase_ (    cls			,				UpperCamelCase			,				UpperCamelCase			,				UpperCamelCase = None			,				UpperCamelCase = "deprecated"			,				)     ->			None:
      os.makedirs(os.path.dirname(UpperCamelCase     )			,				exist_ok=UpperCamelCase     )
      # Prevent parallel extractions
      __lowerCAmelCase												=  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			,				)
         __lowerCAmelCase												=  extractor if extractor != "deprecated" else extractor_format
        else:
         __lowerCAmelCase												=  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'''



# flake8: noqa
# Lint as: python3

from typing import Dict, List, Optional, Type

from .. import config
from ..utils import logging
from .formatting import (
    ArrowFormatter,
    CustomFormatter,
    Formatter,
    PandasFormatter,
    PythonFormatter,
    TensorFormatter,
    format_table,
    query_table,
)
from .np_formatter import NumpyFormatter


lowerCAmelCase	:		List[str]				=   logging.get_logger(__name__)

lowerCAmelCase	:		Dict[Optional[str], Type[Formatter]]				=   {}
lowerCAmelCase	:		Dict[Optional[str], str]				=   {}
lowerCAmelCase	:		Dict[Optional[str], Exception]				=   {}



def   __lowerCAmelCase					(							lowerCamelCase   :						type				,		lowerCamelCase   :						Optional[str]				,		lowerCamelCase   :						Optional[List[str]] = None				,		):






	'''simple docstring'''




	__lowerCAmelCase												=  aliases if aliases is not None else []
	if format_type in _FORMAT_TYPES:
		logger.warning(
		    f'''Overwriting format type \'{format_type}\' ({_FORMAT_TYPES[format_type].__name__} -> {formatter_cls.__name__})'''					)
	__lowerCAmelCase												=  formatter_cls
	for alias in set(aliases + [format_type]					):
		if alias in _FORMAT_TYPES_ALIASES:
			logger.warning(
			    f'''Overwriting format type alias \'{alias}\' ({_FORMAT_TYPES_ALIASES[alias]} -> {format_type})'''					)
		__lowerCAmelCase												=  format_type



def   __lowerCAmelCase					(							lowerCamelCase   :						Exception				,		lowerCamelCase   :						Optional[str]				,		lowerCamelCase   :						Optional[List[str]] = None					):






	'''simple docstring'''




	__lowerCAmelCase												=  aliases if aliases is not None else []
	for alias in set(aliases + [format_type]					):
		__lowerCAmelCase												=  unavailable_error


# Here we define all the available formatting functions that can be used by `Dataset.set_format`
_register_formatter(PythonFormatter, None, aliases=['''python'''])
_register_formatter(ArrowFormatter, '''arrow''', aliases=['''pa''', '''pyarrow'''])
_register_formatter(NumpyFormatter, '''numpy''', aliases=['''np'''])
_register_formatter(PandasFormatter, '''pandas''', aliases=['''pd'''])
_register_formatter(CustomFormatter, '''custom''')

if config.TORCH_AVAILABLE:
	from .torch_formatter import TorchFormatter

	_register_formatter(TorchFormatter, '''torch''', aliases=['''pt''', '''pytorch'''])
else:
	lowerCAmelCase	:		Optional[int]				=   ValueError('''PyTorch needs to be installed to be able to return PyTorch tensors.''')
	_register_unavailable_formatter(_torch_error, '''torch''', aliases=['''pt''', '''pytorch'''])

if config.TF_AVAILABLE:
	from .tf_formatter import TFFormatter

	_register_formatter(TFFormatter, '''tensorflow''', aliases=['''tf'''])
else:
	lowerCAmelCase	:		str				=   ValueError('''Tensorflow needs to be installed to be able to return Tensorflow tensors.''')
	_register_unavailable_formatter(_tf_error, '''tensorflow''', aliases=['''tf'''])

if config.JAX_AVAILABLE:
	from .jax_formatter import JaxFormatter

	_register_formatter(JaxFormatter, '''jax''', aliases=[])
else:
	lowerCAmelCase	:		Any				=   ValueError('''JAX needs to be installed to be able to return JAX arrays.''')
	_register_unavailable_formatter(_jax_error, '''jax''', aliases=[])



def   __lowerCAmelCase					(							lowerCamelCase   :						Optional[str]					):






	'''simple docstring'''




	if format_type in _FORMAT_TYPES_ALIASES:
		return _FORMAT_TYPES_ALIASES[format_type]
	else:
		return format_type




def   __lowerCAmelCase					(							lowerCamelCase   :						Optional[str]				,		**lowerCamelCase   :						Tuple					):






	'''simple docstring'''




	__lowerCAmelCase												=  get_format_type_from_alias(lowerCamelCase					)
	if format_type in _FORMAT_TYPES:
		return _FORMAT_TYPES[format_type](**lowerCamelCase					)
	if format_type in _FORMAT_TYPES_ALIASES_UNAVAILABLE:
		raise _FORMAT_TYPES_ALIASES_UNAVAILABLE[format_type]
	else:
		raise ValueError(
		    f'''Return type should be None or selected in {list(type for type in _FORMAT_TYPES.keys() if type != None					)}, but got \'{format_type}\''''					)