





"""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 		=						get_logger(__name__)
class SCREAMING_SNAKE_CASE_  :






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







							"""simple docstring"""


							snake_case_						:     Tuple     =		(
							    os.path.join(_A						,				config.EXTRACTED_DATASETS_DIR		) if cache_dir else config.EXTRACTED_DATASETS_PATH
							)
							snake_case_						:     Optional[Any]     =		Extractor






						def UpperCAmelCase_			( self : Optional[Any]						,				_A : 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"
							snake_case_						:     int     =		os.path.abspath(_A		)
							return os.path.join(self.extract_dir						,				hash_url_to_filename(_A		)		)






						def UpperCAmelCase_			( self : Union[str, Any]						,				_A : str						,				_A : bool		)							->      bool:







							"""simple docstring"""


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






						def UpperCAmelCase_			( self : int						,				_A : str						,				_A : bool = False		)							->      str:







							"""simple docstring"""


							snake_case_						:     List[Any]     =		self.extractor.infer_extractor_format(_A		)
							if not extractor_format:
								return input_path
							snake_case_						:     Dict     =		self._get_output_path(_A		)
							if self._do_extract(_A						,				_A		):
								self.extractor.extract(_A						,				_A						,				_A		)
							return output_path
class SCREAMING_SNAKE_CASE_  (   snake_case_   ):






						@classmethod
						@abstractmethod
						def UpperCAmelCase_			( cls : Union[str, Any]						,				_A : Union[Path, str]						,				**_A : str		)							->      bool:







							"""simple docstring"""


							...






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







							"""simple docstring"""


							...
class SCREAMING_SNAKE_CASE_  (   snake_case_    ,			snake_case_   ):
						__magic_name__:     List[bytes]	 =    []






						@staticmethod
						def UpperCAmelCase_			( _A : Union[Path, str]						,				_A : int		)							->      Dict:







							"""simple docstring"""


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






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







							"""simple docstring"""


							if not magic_number:
								snake_case_						:     List[str]     =		max(len(_A		) for cls_magic_number in cls.magic_numbers		)
								try:
									snake_case_						:     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 SCREAMING_SNAKE_CASE_  (   snake_case_   ):






						@classmethod
						def UpperCAmelCase_			( cls : Tuple						,				_A : Union[Path, str]						,				**_A : Tuple		)							->      bool:







							"""simple docstring"""


							return tarfile.is_tarfile(_A		)






						@staticmethod
						def UpperCAmelCase_			( _A : Dict						,				_A : str		)							->      Dict:







							"""simple docstring"""


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

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

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

							snake_case_						:     str     =		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 UpperCAmelCase_			( _A : Union[Path, str]						,				_A : Union[Path, str]		)							->      None:







							"""simple docstring"""


							os.makedirs(_A						,				exist_ok=_A		)
							snake_case_						:     Optional[int]     =		tarfile.open(_A		)
							tar_file.extractall(_A						,				members=TarExtractor.safemembers(_A						,				_A		)		)
							tar_file.close()
class SCREAMING_SNAKE_CASE_  (   snake_case_   ):
						__magic_name__:     Any	 =    [B"\x1F\x8B"]






						@staticmethod
						def UpperCAmelCase_			( _A : Union[Path, str]						,				_A : Union[Path, str]		)							->      None:







							"""simple docstring"""


							with gzip.open(_A						,				'rb'		) as gzip_file:
								with open(_A						,				'wb'		) as extracted_file:
									shutil.copyfileobj(_A						,				_A		)
class SCREAMING_SNAKE_CASE_  (   snake_case_   ):
						__magic_name__:     Union[str, Any]	 =    [
						    B"PK\x03\x04",
						    B"PK\x05\x06",  # empty archive
						    B"PK\x07\x08",  # spanned archive
						]






						@classmethod
						def UpperCAmelCase_			( cls : Optional[Any]						,				_A : Union[Path, str]						,				_A : bytes = b""		)							->      bool:







							"""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_						:     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:
												snake_case_						:     Optional[int]     =		fp.read(_A		)  # CD is where we expect it to be
												if len(_A		) == sizeCentralDir:
													snake_case_						:     Optional[int]     =		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 UpperCAmelCase_			( _A : Union[Path, str]						,				_A : Union[Path, str]		)							->      None:







							"""simple docstring"""


							os.makedirs(_A						,				exist_ok=_A		)
							with zipfile.ZipFile(_A						,				'r'		) as zip_file:
								zip_file.extractall(_A		)
								zip_file.close()
class SCREAMING_SNAKE_CASE_  (   snake_case_   ):
						__magic_name__:     str	 =    [B"\xFD\x37\x7A\x58\x5A\x00"]






						@staticmethod
						def UpperCAmelCase_			( _A : Union[Path, str]						,				_A : Union[Path, str]		)							->      None:







							"""simple docstring"""


							with lzma.open(_A		) as compressed_file:
								with open(_A						,				'wb'		) as extracted_file:
									shutil.copyfileobj(_A						,				_A		)
class SCREAMING_SNAKE_CASE_  (   snake_case_   ):
						__magic_name__:     Any	 =    [B"Rar!\x1a\x07\x00", B"Rar!\x1a\x07\x01\x00"]  # RAR_ID  # RAR5_ID






						@staticmethod
						def UpperCAmelCase_			( _A : Union[Path, str]						,				_A : Union[Path, str]		)							->      None:







							"""simple docstring"""


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

							os.makedirs(_A						,				exist_ok=_A		)
							snake_case_						:     Optional[Any]     =		rarfile.RarFile(_A		)
							rf.extractall(_A		)
							rf.close()
class SCREAMING_SNAKE_CASE_  (   snake_case_   ):
						__magic_name__:     Optional[int]	 =    [B"\x28\xb5\x2F\xFD"]






						@staticmethod
						def UpperCAmelCase_			( _A : Union[Path, str]						,				_A : Union[Path, str]		)							->      None:







							"""simple docstring"""


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

							snake_case_						:     int     =		zstd.ZstdDecompressor()
							with open(_A						,				'rb'		) as ifh, open(_A						,				'wb'		) as ofh:
								dctx.copy_stream(_A						,				_A		)
class SCREAMING_SNAKE_CASE_  (   snake_case_   ):
						__magic_name__:     List[str]	 =    [B"\x42\x5A\x68"]






						@staticmethod
						def UpperCAmelCase_			( _A : Union[Path, str]						,				_A : Union[Path, str]		)							->      None:







							"""simple docstring"""


							with bza.open(_A						,				'rb'		) as compressed_file:
								with open(_A						,				'wb'		) as extracted_file:
									shutil.copyfileobj(_A						,				_A		)
class SCREAMING_SNAKE_CASE_  (   snake_case_   ):
						__magic_name__:     Optional[Any]	 =    [B"\x37\x7A\xBC\xAF\x27\x1C"]






						@staticmethod
						def UpperCAmelCase_			( _A : Union[Path, str]						,				_A : Union[Path, str]		)							->      None:







							"""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 SCREAMING_SNAKE_CASE_  (   snake_case_   ):
						__magic_name__:     Optional[int]	 =    [B"\x04\x22\x4D\x18"]






						@staticmethod
						def UpperCAmelCase_			( _A : Union[Path, str]						,				_A : Union[Path, str]		)							->      None:







							"""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 SCREAMING_SNAKE_CASE_  :
						#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
						__magic_name__:     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 : Union[str, Any]		)							->      List[Any]:







							"""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 UpperCAmelCase_			( _A : Union[Path, str]						,				_A : int		)							->      List[str]:







							"""simple docstring"""


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






						@classmethod
						def UpperCAmelCase_			( cls : int						,				_A : Union[Path, str]						,				_A : 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=_A						,				)
							snake_case_						:     Any     =		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 UpperCAmelCase_			( cls : str						,				_A : Union[Path, str]		)							->      str:  # <Added version="2.4.0"/>







							"""simple docstring"""


							snake_case_						:     Optional[int]     =		cls._get_magic_number_max_length()
							snake_case_						:     List[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 UpperCAmelCase_			( cls : Union[str, Any]						,				_A : Union[Path, str]						,				_A : Union[Path, str]						,				_A : Optional[str] = None						,				_A : Optional[BaseExtractor] = "deprecated"						,				)							->      None:







							"""simple docstring"""


							os.makedirs(os.path.dirname(_A		)						,				exist_ok=_A		)
							# Prevent parallel extractions
							snake_case_						:     Tuple     =		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_						:     int     =		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		)








from typing import TYPE_CHECKING

from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_SCREAMING_SNAKE_CASE 		=						{
    """configuration_mctct""": ["""MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MCTCTConfig"""],
    """feature_extraction_mctct""": ["""MCTCTFeatureExtractor"""],
    """processing_mctct""": ["""MCTCTProcessor"""],
}


try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						_SCREAMING_SNAKE_CASE 		=						[
						    """MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST""",
						    """MCTCTForCTC""",
						    """MCTCTModel""",
						    """MCTCTPreTrainedModel""",
						]


if TYPE_CHECKING:
						from .configuration_mctct import MCTCT_PRETRAINED_CONFIG_ARCHIVE_MAP, MCTCTConfig
						from .feature_extraction_mctct import MCTCTFeatureExtractor
						from .processing_mctct import MCTCTProcessor

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_mctct import MCTCT_PRETRAINED_MODEL_ARCHIVE_LIST, MCTCTForCTC, MCTCTModel, MCTCTPreTrainedModel

else:
						import sys

						_SCREAMING_SNAKE_CASE 		=						_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

