


'''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__    	=     get_logger(__name__)






class 	lowerCAmelCase__			:




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



					'''simple docstring'''







					_UpperCAmelCase		:       Any								=      (
					    os.path.join(lowerCamelCase__	,  config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH
					)
					_UpperCAmelCase		:       Tuple								=      Extractor




			def 							lowerCAmelCase__    (		self  :     Optional[int]	,  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"
					_UpperCAmelCase		:       Dict								=      os.path.abspath(lowerCamelCase__ )
					return os.path.join(self.extract_dir	,  hash_url_to_filename(lowerCamelCase__ ) )




			def 							lowerCAmelCase__    (		self  :     int	,  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  :     Optional[Any]	,  lowerCamelCase__  :     str	,  lowerCamelCase__  :     bool = False )   ->str:



					'''simple docstring'''







					_UpperCAmelCase		:       Union[str, Any]								=      self.extractor.infer_extractor_format(lowerCamelCase__ )
					if not extractor_format:
							return input_path
					_UpperCAmelCase		:       List[Any]								=      self._get_output_path(lowerCamelCase__ )
					if self._do_extract(lowerCamelCase__	,  lowerCamelCase__ ):
							self.extractor.extract(lowerCamelCase__	,  lowerCamelCase__	,  lowerCamelCase__ )
					return output_path






class 	lowerCAmelCase__			(			UpperCAmelCase__	):




			@classmethod
			@abstractmethod
			def 							lowerCAmelCase__    (		cls  :     List[Any]	,  lowerCamelCase__  :     Union[Path, str]	,  **lowerCamelCase__  :     Optional[Any] )   ->bool:



					'''simple docstring'''







					...






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



					'''simple docstring'''







					...






class 	lowerCAmelCase__			(			UpperCAmelCase__    ,       UpperCAmelCase__	):
			lowerCAmelCase :	List[bytes]          =     []




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



					'''simple docstring'''







					with open(lowerCamelCase__	,  "rb" ) as f:
							return f.read(lowerCamelCase__ )






			@classmethod
			def 							lowerCAmelCase__    (		cls  :     List[str]	,  lowerCamelCase__  :     Union[Path, str]	,  lowerCamelCase__  :     bytes = b"" )   ->bool:



					'''simple docstring'''







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




			@classmethod
			def 							lowerCAmelCase__    (		cls  :     List[str]	,  lowerCamelCase__  :     Union[Path, str]	,  **lowerCamelCase__  :     Any )   ->bool:



					'''simple docstring'''







					return tarfile.is_tarfile(lowerCamelCase__ )




			@staticmethod
			def 							lowerCAmelCase__    (		lowerCamelCase__  :     Tuple	,  lowerCamelCase__  :     List[Any] )   ->Optional[int]:



					'''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__  :     Any	,  lowerCamelCase__  :     str ) -> bool:
							# Links are interpreted relative to the directory containing the link
							_UpperCAmelCase		:       List[Any]								=      resolved(os.path.join(lowerCamelCase__	,  os.path.dirname(info.name ) ) )
							return badpath(info.linkname	,  base=lowerCamelCase__ )

					_UpperCAmelCase		:       int								=      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__ )
					_UpperCAmelCase		:       Any								=      tarfile.open(lowerCamelCase__ )
					tar_file.extractall(lowerCamelCase__	,  members=TarExtractor.safemembers(lowerCamelCase__	,  lowerCamelCase__ ) )
					tar_file.close()






class 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	Any          =     [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 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	List[Any]          =     [
			    b"PK\x03\x04",
			    b"PK\x05\x06",  # empty archive
			    b"PK\x07\x08",  # spanned archive
			]




			@classmethod
			def 							lowerCAmelCase__    (		cls  :     str	,  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:
									_UpperCAmelCase		:       List[Any]								=      _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:
															_UpperCAmelCase		:       Tuple								=      fp.read(lowerCamelCase__ )  # CD is where we expect it to be
															if len(lowerCamelCase__ ) == sizeCentralDir:
																	_UpperCAmelCase		:       List[str]								=      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 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	List[str]          =     [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 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	str          =     [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__ )
					_UpperCAmelCase		:       int								=      rarfile.RarFile(lowerCamelCase__ )
					rf.extractall(lowerCamelCase__ )
					rf.close()






class 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	Dict          =     [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

					_UpperCAmelCase		:       Tuple								=      zstd.ZstdDecompressor()
					with open(lowerCamelCase__	,  "rb" ) as ifh, open(lowerCamelCase__	,  "wb" ) as ofh:
							dctx.copy_stream(lowerCamelCase__	,  lowerCamelCase__ )






class 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	str          =     [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 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	List[str]          =     [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 	lowerCAmelCase__			(			UpperCAmelCase__	):
			lowerCAmelCase :	List[Any]          =     [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 	lowerCAmelCase__			:
			#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
			lowerCAmelCase :	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 							lowerCAmelCase__    (		cls  :     str )   ->Dict:



					'''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 )   ->Any:



					'''simple docstring'''







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




			@classmethod
			def 							lowerCAmelCase__    (		cls  :     Tuple	,  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__	,  )
					_UpperCAmelCase		:       Tuple								=      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__  :     Union[Path, str] )   ->str:  # <Added version="2.4.0"/>



					'''simple docstring'''







					_UpperCAmelCase		:       Union[str, Any]								=      cls._get_magic_number_max_length()
					_UpperCAmelCase		:       Optional[Any]								=      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[int]	,  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
					_UpperCAmelCase		:       List[str]								=      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__	,  )
											_UpperCAmelCase		:       Optional[Any]								=      extractor if extractor != "deprecated" else extractor_format
									else:
											_UpperCAmelCase		:       List[str]								=      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'''


# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run

import sys
import warnings
from os.path import abspath, dirname, join


# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
lowerCamelCase__    	=     abspath(join(dirname(dirname(dirname(__file__))), 'src'))
sys.path.insert(1, git_repo_path)


# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action='ignore', category=FutureWarning)






def  __lowerCAmelCase (__lowerCAmelCase   ):
		from transformers.testing_utils import pytest_addoption_shared

		pytest_addoption_shared(__lowerCAmelCase   )






def  __lowerCAmelCase (__lowerCAmelCase   ):
		from transformers.testing_utils import pytest_terminal_summary_main

		_UpperCAmelCase		:       Optional[int]								=      terminalreporter.config.getoption("--make-reports"   )
		if make_reports:
				pytest_terminal_summary_main(__lowerCAmelCase      , id=__lowerCAmelCase   )



