




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


_snake_case : Dict  				=						get_logger(__name__)

class      A       :







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


														"""simple docstring"""


														_a      	=							(
														    os.path.join(lowerCAmelCase_				,     config.EXTRACTED_DATASETS_DIR   ) if cache_dir else config.EXTRACTED_DATASETS_PATH
														)
														_a      	=							Extractor







							def   __lowerCAmelCase     (    self			:    Optional[Any]				,     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"
														_a      	=							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			:    int				,     lowerCAmelCase_			:    str				,     lowerCAmelCase_			:    bool = False   )     ->				str:


														"""simple docstring"""


														_a      	=							self.extractor.infer_extractor_format(lowerCAmelCase_   )
														if not extractor_format:
																					return input_path
														_a      	=							self._get_output_path(lowerCAmelCase_   )
														if self._do_extract(lowerCAmelCase_				,     lowerCAmelCase_   ):
																					self.extractor.extract(lowerCAmelCase_				,     lowerCAmelCase_				,     lowerCAmelCase_   )
														return output_path



class      A       (						_a       ):







							@classmethod
							@abstractmethod
							def   __lowerCAmelCase     (    cls			:    Optional[int]				,     lowerCAmelCase_			:    Union[Path, str]				,     **lowerCAmelCase_			:    int   )     ->				bool:


														"""simple docstring"""


														...







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


														"""simple docstring"""


														...



class      A       (						_a	,_a       ):
							lowercase_							     =							[]







							@staticmethod
							def   __lowerCAmelCase     (    lowerCAmelCase_			:    Union[Path, str]				,     lowerCAmelCase_			:    int   )     ->				Union[str, Any]:


														"""simple docstring"""


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







							@classmethod
							def   __lowerCAmelCase     (    cls			:    Dict				,     lowerCAmelCase_			:    Union[Path, str]				,     lowerCAmelCase_			:    bytes = b""   )     ->				bool:


														"""simple docstring"""


														if not magic_number:
																					_a      	=							max(len(lowerCAmelCase_   ) for cls_magic_number in cls.magic_numbers   )
																					try:
																												_a      	=							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       (						_a       ):







							@classmethod
							def   __lowerCAmelCase     (    cls			:    int				,     lowerCAmelCase_			:    Union[Path, str]				,     **lowerCAmelCase_			:    Union[str, Any]   )     ->				bool:


														"""simple docstring"""


														return tarfile.is_tarfile(lowerCAmelCase_   )







							@staticmethod
							def   __lowerCAmelCase     (    lowerCAmelCase_			:    List[Any]				,     lowerCAmelCase_			:    Tuple   )     ->				Dict:


														"""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_			:    str				,     lowerCAmelCase_			:    str   ) -> bool:
																					# Links are interpreted relative to the directory containing the link
																					_a      	=							resolved(os.path.join(lowerCAmelCase_				,     os.path.dirname(info.name   )   )   )
																					return badpath(info.linkname				,     base=lowerCAmelCase_   )

														_a      	=							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_   )
														_a      	=							tarfile.open(lowerCAmelCase_   )
														tar_file.extractall(lowerCAmelCase_				,     members=TarExtractor.safemembers(lowerCAmelCase_				,     lowerCAmelCase_   )   )
														tar_file.close()



class      A       (						_a       ):
							lowercase_							     =							[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       (						_a       ):
							lowercase_							     =							[
							    b'PK\x03\x04',
							    b'PK\x05\x06',  # empty archive
							    b'PK\x07\x08',  # spanned archive
							]







							@classmethod
							def   __lowerCAmelCase     (    cls			:    Optional[int]				,     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:
																												_a      	=							_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:
																																																	_a      	=							fp.read(lowerCAmelCase_   )  # CD is where we expect it to be
																																																	if len(lowerCAmelCase_   ) == sizeCentralDir:
																																																								_a      	=							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       (						_a       ):
							lowercase_							     =							[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       (						_a       ):
							lowercase_							     =							[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_   )
														_a      	=							rarfile.RarFile(lowerCAmelCase_   )
														rf.extractall(lowerCAmelCase_   )
														rf.close()



class      A       (						_a       ):
							lowercase_							     =							[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

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



class      A       (						_a       ):
							lowercase_							     =							[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       (						_a       ):
							lowercase_							     =							[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       (						_a       ):
							lowercase_							     =							[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)
							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			:    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   )     ->				List[Any]:


														"""simple docstring"""


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







							@classmethod
							def   __lowerCAmelCase     (    cls			:    int				,     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_				,     )
														_a      	=							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			:    Optional[int]				,     lowerCAmelCase_			:    Union[Path, str]   )     ->				str:  # <Added version="2.4.0"/>


														"""simple docstring"""


														_a      	=							cls._get_magic_number_max_length()
														_a      	=							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			:    Optional[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
														_a      	=							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_				,     )
																																			_a      	=							extractor if extractor != '''deprecated''' else extractor_format
																												else:
																																			_a      	=							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 pytest

from datasets.splits import SplitDict, SplitInfo
from datasets.utils.py_utils import asdict
@pytest.mark.parametrize(
    '''split_dict'''					,		[
        SplitDict(),
        SplitDict({'''train''': SplitInfo(name='''train'''					,		num_bytes=1337					,		num_examples=42					,		dataset_name='''my_dataset''' )} ),
        SplitDict({'''train''': SplitInfo(name='''train'''					,		num_bytes=1337					,		num_examples=42 )} ),
        SplitDict({'''train''': SplitInfo()} ),
    ]					,		)
def 						snake_case_       (UpperCamelCase			:    SplitDict ):





							'''simple docstring'''


							_a      	=							split_dict._to_yaml_list()
							assert len(UpperCamelCase ) == len(UpperCamelCase )
							_a      	=							SplitDict._from_yaml_list(UpperCamelCase )
							for split_name, split_info in split_dict.items():
														# dataset_name field is deprecated, and is therefore not part of the YAML dump
														_a      	=							None
														# the split name of split_dict takes over the name of the split info object
														_a      	=							split_name
							assert split_dict == reloaded

@pytest.mark.parametrize(
    '''split_info'''					,		[SplitInfo(), SplitInfo(dataset_name=UpperCamelCase ), SplitInfo(dataset_name='''my_dataset''' )] )
def 						snake_case_       (UpperCamelCase			:    List[str] ):





							'''simple docstring'''


							_a      	=							asdict(SplitDict({'''train''': split_info} ) )
							assert "dataset_name" in split_dict_asdict["train"]
							assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name

