

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   __lowercase    :




			"""simple docstring"""







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



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Optional[Any]       ,						lowerCAmelCase__  :					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"
									SCREAMING_SNAKE_CASE_:			List[str]  		=	os.path.abspath(lowerCAmelCase__)
									return os.path.join(self.extract_dir       ,						hash_url_to_filename(lowerCAmelCase__))



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Dict       ,						lowerCAmelCase__  :					str       ,						lowerCAmelCase__  :					bool):
									return force_extract or (
									    not os.path.isfile(lowerCAmelCase__) and not (os.path.isdir(lowerCAmelCase__) and os.listdir(lowerCAmelCase__))
									)




			def 	_SCREAMING_SNAKE_CASE      (			self  :					Union[str, Any]       ,						lowerCAmelCase__  :					str       ,						lowerCAmelCase__  :					bool = False):
									SCREAMING_SNAKE_CASE_:			Dict  		=	self.extractor.infer_extractor_format(lowerCAmelCase__)
									if not extractor_format:
															return input_path
									SCREAMING_SNAKE_CASE_:			str  		=	self._get_output_path(lowerCAmelCase__)
									if self._do_extract(lowerCAmelCase__       ,						lowerCAmelCase__):
															self.extractor.extract(lowerCAmelCase__       ,						lowerCAmelCase__       ,						lowerCAmelCase__)
									return output_path







class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			@classmethod
			@abstractmethod
			def 	_SCREAMING_SNAKE_CASE      (			cls  :					str       ,						lowerCAmelCase__  :					Union[Path, str]       ,						**lowerCAmelCase__  :					str):
									...




			@staticmethod
			@abstractmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					Union[Path, str]):
									...







class   __lowercase    (			UpperCAmelCase_		,	UpperCAmelCase_     ):




			"""simple docstring"""







			_UpperCAmelCase       :							List[bytes]      							=					[]



			@staticmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					int):
									with open(lowerCAmelCase__       ,						"rb") as f:
															return f.read(lowerCAmelCase__)




			@classmethod
			def 	_SCREAMING_SNAKE_CASE      (			cls  :					List[Any]       ,						lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					bytes = b""):
									if not magic_number:
															SCREAMING_SNAKE_CASE_:			Dict  		=	max(len(lowerCAmelCase__) for cls_magic_number in cls.magic_numbers)
															try:
																					SCREAMING_SNAKE_CASE_:			Optional[int]  		=	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   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			@classmethod
			def 	_SCREAMING_SNAKE_CASE      (			cls  :					Optional[int]       ,						lowerCAmelCase__  :					Union[Path, str]       ,						**lowerCAmelCase__  :					Tuple):
									return tarfile.is_tarfile(lowerCAmelCase__)



			@staticmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Optional[Any]       ,						lowerCAmelCase__  :					List[str]):

									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
															SCREAMING_SNAKE_CASE_:			Dict  		=	resolved(os.path.join(lowerCAmelCase__       ,						os.path.dirname(info.name)))
															return badpath(info.linkname       ,						base=lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_:			Union[str, Any]  		=	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 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					Union[Path, str]):
									os.makedirs(lowerCAmelCase__       ,						exist_ok=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	tarfile.open(lowerCAmelCase__)
									tar_file.extractall(lowerCAmelCase__       ,						members=TarExtractor.safemembers(lowerCAmelCase__       ,						lowerCAmelCase__))
									tar_file.close()







class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			_UpperCAmelCase       :							Optional[Any]      							=					[b'''\x1F\x8B''']



			@staticmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					Union[Path, str]):
									with gzip.open(lowerCAmelCase__       ,						"rb") as gzip_file:
															with open(lowerCAmelCase__       ,						"wb") as extracted_file:
																					shutil.copyfileobj(lowerCAmelCase__       ,						lowerCAmelCase__)







class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







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



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







class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			_UpperCAmelCase       :							Tuple      							=					[b'''\xFD\x37\x7A\x58\x5A\x00''']



			@staticmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					Union[Path, str]):
									with lzma.open(lowerCAmelCase__) as compressed_file:
															with open(lowerCAmelCase__       ,						"wb") as extracted_file:
																					shutil.copyfileobj(lowerCAmelCase__       ,						lowerCAmelCase__)







class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			_UpperCAmelCase       :							Optional[int]      							=					[b'''Rar!\x1a\x07\x00''', b'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID



			@staticmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					Union[Path, str]):
									if not config.RARFILE_AVAILABLE:
															raise ImportError("Please pip install rarfile")
									import rarfile

									os.makedirs(lowerCAmelCase__       ,						exist_ok=lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	rarfile.RarFile(lowerCAmelCase__)
									rf.extractall(lowerCAmelCase__)
									rf.close()







class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







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



			@staticmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					Union[Path, str]):
									if not config.ZSTANDARD_AVAILABLE:
															raise ImportError("Please pip install zstandard")
									import zstandard as zstd

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







class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







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



			@staticmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					Union[Path, str]):
									with bza.open(lowerCAmelCase__       ,						"rb") as compressed_file:
															with open(lowerCAmelCase__       ,						"wb") as extracted_file:
																					shutil.copyfileobj(lowerCAmelCase__       ,						lowerCAmelCase__)







class   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			_UpperCAmelCase       :							Tuple      							=					[b'''\x37\x7A\xBC\xAF\x27\x1C''']



			@staticmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					Union[Path, str]):
									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   __lowercase    (			UpperCAmelCase_     ):




			"""simple docstring"""







			_UpperCAmelCase       :							Tuple      							=					[b'''\x04\x22\x4D\x18''']



			@staticmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					Union[Path, str]):
									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   __lowercase    :




			"""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 	_SCREAMING_SNAKE_CASE      (			cls  :					List[Any]):
									return max(
									    len(lowerCAmelCase__)
									    for extractor in cls.extractors.values()
									    if issubclass(lowerCAmelCase__       ,						lowerCAmelCase__)
									    for extractor_magic_number in extractor.magic_numbers)



			@staticmethod
			def 	_SCREAMING_SNAKE_CASE      (			lowerCAmelCase__  :					Union[Path, str]       ,						lowerCAmelCase__  :					int):
									try:
															return MagicNumberBaseExtractor.read_magic_number(lowerCAmelCase__       ,						magic_number_length=lowerCAmelCase__)
									except OSError:
															return b""



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








from __future__ import annotations

from collections import deque
from collections.abc import Iterator
from dataclasses import dataclass



@dataclass
class   __lowercase    :




			"""simple docstring"""







			_UpperCAmelCase       :							int
			_UpperCAmelCase       :							int







class   __lowercase    :




			"""simple docstring"""







			def __init__(			self  :					Any       ,						lowerCAmelCase__  :					int):
									SCREAMING_SNAKE_CASE_:			list[list[Edge]]  		=	[[] for _ in range(lowerCAmelCase__)]
									SCREAMING_SNAKE_CASE_:			Dict  		=	size



			def __getitem__(			self  :					Dict       ,						lowerCAmelCase__  :					int):
									return iter(self._graph[vertex])



			@property
			def 	_SCREAMING_SNAKE_CASE      (			self  :					Tuple):
									return self._size



			def 	_SCREAMING_SNAKE_CASE      (			self  :					Dict       ,						lowerCAmelCase__  :					int       ,						lowerCAmelCase__  :					int       ,						lowerCAmelCase__  :					int):
									if weight not in (0, 1):
															raise ValueError("Edge weight must be either 0 or 1.")

									if to_vertex < 0 or to_vertex >= self.size:
															raise ValueError("Vertex indexes must be in [0; size).")

									self._graph[from_vertex].append(Edge(lowerCAmelCase__       ,						lowerCAmelCase__))




			def 	_SCREAMING_SNAKE_CASE      (			self  :					List[Any]       ,						lowerCAmelCase__  :					int       ,						lowerCAmelCase__  :					int):
									SCREAMING_SNAKE_CASE_:			Optional[int]  		=	deque([start_vertex])
									SCREAMING_SNAKE_CASE_:			list[int | None]  		=	[None] * self.size
									SCREAMING_SNAKE_CASE_:			List[Any]  		=	0

									while queue:
															SCREAMING_SNAKE_CASE_:			int  		=	queue.popleft()
															SCREAMING_SNAKE_CASE_:			str  		=	distances[current_vertex]
															if current_distance is None:
																					continue

															for edge in self[current_vertex]:
																					SCREAMING_SNAKE_CASE_:			Optional[int]  		=	current_distance + edge.weight
																					SCREAMING_SNAKE_CASE_:			str  		=	distances[edge.destination_vertex]
																					if (
																					    isinstance(lowerCAmelCase__       ,						lowerCAmelCase__)
																					    and new_distance >= dest_vertex_distance
																					):
																											continue
																					SCREAMING_SNAKE_CASE_:			Any  		=	new_distance
																					if edge.weight == 0:
																											queue.appendleft(edge.destination_vertex)
																					else:
																											queue.append(edge.destination_vertex)

									if distances[finish_vertex] is None:
															raise ValueError("No path from start_vertex to finish_vertex.")

									return distances[finish_vertex]


if __name__ == "__main__":
						import doctest

						doctest.testmod()






