

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


A_       : str         =			get_logger(__name__)



class     _a						:


					'''simple docstring'''






					def __init__( self    ,       A__ = None			):
						A__							:    Tuple        =		(
						    os.path.join(A__    ,       config.EXTRACTED_DATASETS_DIR			) if cache_dir else config.EXTRACTED_DATASETS_PATH
						)
						A__							:    Optional[Any]        =		Extractor






					def   __A			( self    ,       A__			):
						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__							:    Optional[Any]        =		os.path.abspath(A__			)
						return os.path.join(self.extract_dir    ,       hash_url_to_filename(A__			)			)






					def   __A			( self    ,       A__    ,       A__			):
						return force_extract or (
						    not os.path.isfile(A__			) and not (os.path.isdir(A__			) and os.listdir(A__			))
						)






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



class     _a						(__magic_name__				):


					'''simple docstring'''






					@classmethod
					@abstractmethod
					def   __A			( cls    ,       A__    ,       **A__			):
						...






					@staticmethod
					@abstractmethod
					def   __A			( A__    ,       A__			):
						...



class     _a						(__magic_name__		,   __magic_name__				):


					'''simple docstring'''






					UpperCAmelCase__:   List[bytes]  							=       []






					@staticmethod
					def   __A			( A__    ,       A__			):
						with open(A__    ,       """rb"""			) as f:
							return f.read(A__			)






					@classmethod
					def   __A			( cls    ,       A__    ,       A__ = b""			):
						if not magic_number:
							A__							:    Tuple        =		max(len(A__			) for cls_magic_number in cls.magic_numbers			)
							try:
								A__							:    List[Any]        =		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     _a						(__magic_name__				):


					'''simple docstring'''






					@classmethod
					def   __A			( cls    ,       A__    ,       **A__			):
						return tarfile.is_tarfile(A__			)






					@staticmethod
					def   __A			( A__    ,       A__			):

						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
							A__							:    Optional[Any]        =		resolved(os.path.join(A__    ,       os.path.dirname(info.name			)			)			)
							return badpath(info.linkname    ,       base=A__			)

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



class     _a						(__magic_name__				):


					'''simple docstring'''






					UpperCAmelCase__:   Union[str, Any]  							=       [b'''\x1F\x8B''']






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



class     _a						(__magic_name__				):


					'''simple docstring'''






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






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



class     _a						(__magic_name__				):


					'''simple docstring'''






					UpperCAmelCase__:   Optional[Any]  							=       [b'''\xFD\x37\x7A\x58\x5A\x00''']






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



class     _a						(__magic_name__				):


					'''simple docstring'''






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






					@staticmethod
					def   __A			( A__    ,       A__			):
						if not config.RARFILE_AVAILABLE:
							raise ImportError("""Please pip install rarfile"""			)
						import rarfile

						os.makedirs(A__    ,       exist_ok=A__			)
						A__							:    Any        =		rarfile.RarFile(A__			)
						rf.extractall(A__			)
						rf.close()



class     _a						(__magic_name__				):


					'''simple docstring'''






					UpperCAmelCase__:   Dict  							=       [b'''\x28\xb5\x2F\xFD''']






					@staticmethod
					def   __A			( A__    ,       A__			):
						if not config.ZSTANDARD_AVAILABLE:
							raise ImportError("""Please pip install zstandard"""			)
						import zstandard as zstd

						A__							:    List[Any]        =		zstd.ZstdDecompressor()
						with open(A__    ,       """rb"""			) as ifh, open(A__    ,       """wb"""			) as ofh:
							dctx.copy_stream(A__    ,       A__			)



class     _a						(__magic_name__				):


					'''simple docstring'''






					UpperCAmelCase__:   Dict  							=       [b'''\x42\x5A\x68''']






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



class     _a						(__magic_name__				):


					'''simple docstring'''






					UpperCAmelCase__:   Union[str, Any]  							=       [b'''\x37\x7A\xBC\xAF\x27\x1C''']






					@staticmethod
					def   __A			( A__    ,       A__			):
						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     _a						(__magic_name__				):


					'''simple docstring'''






					UpperCAmelCase__:   Optional[Any]  							=       [b'''\x04\x22\x4D\x18''']






					@staticmethod
					def   __A			( A__    ,       A__			):
						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     _a						:


					'''simple docstring'''






					UpperCAmelCase__:   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			):
						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__    ,       A__			):
						try:
							return MagicNumberBaseExtractor.read_magic_number(A__    ,       magic_number_length=A__			)
						except OSError:
							return b""






					@classmethod
					def   __A			( cls    ,       A__    ,       A__ = 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=A__    ,       )
						A__							:    List[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   __A			( cls    ,       A__			):  # <Added version="2.4.0"/>
						A__							:    Optional[int]        =		cls._get_magic_number_max_length()
						A__							:    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   __A			( cls    ,       A__    ,       A__    ,       A__ = None    ,       A__ = "deprecated"    ,       ):
						os.makedirs(os.path.dirname(A__			)    ,       exist_ok=A__			)
						# Prevent parallel extractions
						A__							:    str        =		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__    ,       )
									A__							:    Union[str, Any]        =		extractor if extractor != """deprecated""" else extractor_format
								else:
									A__							:    str        =		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__			)






import os

import pytest
import yaml

from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict

@pytest.mark.parametrize(
    """files"""    ,      [
        ["""full:README.md""", """dataset_infos.json"""],
        ["""empty:README.md""", """dataset_infos.json"""],
        ["""dataset_infos.json"""],
        ["""full:README.md"""],
    ]    ,      )
def 						UpperCamelCase					(lowercase_: List[str]    ,      lowercase_: Optional[int]					)     ->      List[str]:
	A__							:    Tuple        =		tmp_path_factory.mktemp("""dset_infos_dir"""					)
	if "full:README.md" in files:
		with open(dataset_infos_dir / """README.md"""    ,      """w"""					) as f:
			f.write("""---\ndataset_info:\n  dataset_size: 42\n---"""					)
	if "empty:README.md" in files:
		with open(dataset_infos_dir / """README.md"""    ,      """w"""					) as f:
			f.write(""""""					)
    # we want to support dataset_infos.json for backward compatibility
	if "dataset_infos.json" in files:
		with open(dataset_infos_dir / """dataset_infos.json"""    ,      """w"""					) as f:
			f.write("""{\"default\": {\"dataset_size\": 42}}"""					)
	A__							:    List[Any]        =		DatasetInfosDict.from_directory(lowercase_					)
	assert dataset_infos
	assert dataset_infos["default"].dataset_size == 42

@pytest.mark.parametrize(
    """dataset_info"""    ,      [
        DatasetInfo(),
        DatasetInfo(
            description="""foo"""    ,      features=Features({"""a""": Value("""int32"""					)}					)    ,      builder_name="""builder"""    ,      config_name="""config"""    ,      version="""1.0.0"""    ,      splits=[{"""name""": """train"""}]    ,      download_size=42    ,      ),
    ]    ,      )
def 						UpperCamelCase					(lowercase_: str    ,      lowercase_: DatasetInfo					)     ->      List[Any]:
	A__							:    Union[str, Any]        =		str(lowercase_					)
	dataset_info.write_to_directory(lowercase_					)
	A__							:    List[Any]        =		DatasetInfo.from_directory(lowercase_					)
	assert dataset_info == reloaded
	assert os.path.exists(os.path.join(lowercase_    ,      """dataset_info.json"""					)					)

def 						UpperCamelCase					()     ->      List[Any]:
	A__							:    Union[str, Any]        =		DatasetInfo(
	    description="""foo"""    ,      citation="""bar"""    ,      homepage="""https://foo.bar"""    ,      license="""CC0"""    ,      features=Features({"""a""": Value("""int32"""					)}					)    ,      post_processed={}    ,      supervised_keys=()    ,      task_templates=[]    ,      builder_name="""builder"""    ,      config_name="""config"""    ,      version="""1.0.0"""    ,      splits=[{"""name""": """train""", """num_examples""": 42}]    ,      download_checksums={}    ,      download_size=1337    ,      post_processing_size=442    ,      dataset_size=1234    ,      size_in_bytes=1337 + 442 + 1234    ,      )
	A__							:    Dict        =		dataset_info._to_yaml_dict()
	assert sorted(lowercase_					) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML					)
	for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
		assert key in dataset_info_yaml_dict
		assert isinstance(dataset_info_yaml_dict[key]    ,      (list, dict, int, str)					)
	A__							:    Union[str, Any]        =		yaml.safe_dump(lowercase_					)
	A__							:    List[Any]        =		yaml.safe_load(lowercase_					)
	assert dataset_info_yaml_dict == reloaded

def 						UpperCamelCase					()     ->      List[str]:
	A__							:    Optional[int]        =		DatasetInfo()
	A__							:    List[Any]        =		dataset_info._to_yaml_dict()
	assert dataset_info_yaml_dict == {}


@pytest.mark.parametrize(
    """dataset_infos_dict"""    ,      [
        DatasetInfosDict(),
        DatasetInfosDict({"""default""": DatasetInfo()}					),
        DatasetInfosDict({"""my_config_name""": DatasetInfo()}					),
        DatasetInfosDict(
            {
                """default""": DatasetInfo(
                    description="""foo"""    ,      features=Features({"""a""": Value("""int32"""					)}					)    ,      builder_name="""builder"""    ,      config_name="""config"""    ,      version="""1.0.0"""    ,      splits=[{"""name""": """train"""}]    ,      download_size=42    ,      )
            }					),
        DatasetInfosDict(
            {
                """v1""": DatasetInfo(dataset_size=42					),
                """v2""": DatasetInfo(dataset_size=1337					),
            }					),
    ]    ,      )
def 						UpperCamelCase					(lowercase_: Tuple    ,      lowercase_: DatasetInfosDict					)     ->      Optional[Any]:
	A__							:    List[Any]        =		str(lowercase_					)
	dataset_infos_dict.write_to_directory(lowercase_					)
	A__							:    Dict        =		DatasetInfosDict.from_directory(lowercase_					)

	# the config_name of the dataset_infos_dict take over the attribute
	for config_name, dataset_info in dataset_infos_dict.items():
		A__							:    Optional[int]        =		config_name
		# the yaml representation doesn't include fields like description or citation
		# so we just test that we can recover what we can from the yaml
		A__							:    List[str]        =		DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict()					)
	assert dataset_infos_dict == reloaded

	if dataset_infos_dict:
		assert os.path.exists(os.path.join(lowercase_    ,      """README.md"""					)					)



