



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

class        UpperCAmelCase_  :

						'''simple docstring'''




						def __init__(   self				,							_A = None		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= (
													    os.path.join(_A				,							config.EXTRACTED_DATASETS_DIR		) if cache_dir else config.EXTRACTED_DATASETS_PATH
													)
													__SCREAMING_SNAKE_CASE									= Extractor






						def 	_A     (   self				,							_A		):







													'''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"
													__SCREAMING_SNAKE_CASE									= os.path.abspath(_A		)
													return os.path.join(self.extract_dir				,							hash_url_to_filename(_A		)		)






						def 	_A     (   self				,							_A				,							_A		):







													'''simple docstring'''

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







													'''simple docstring'''

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







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						@classmethod
						@abstractmethod
						def 	_A     (   cls				,							_A				,							**_A		):







													'''simple docstring'''

													...






						@staticmethod
						@abstractmethod
						def 	_A     (   _A				,							_A		):







													'''simple docstring'''

													...







class        UpperCAmelCase_  (       UpperCamelCase_   ,   UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			List[bytes]      =  []






						@staticmethod
						def 	_A     (   _A				,							_A		):







													'''simple docstring'''

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






						@classmethod
						def 	_A     (   cls				,							_A				,							_A = b""		):







													'''simple docstring'''

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

						'''simple docstring'''




						@classmethod
						def 	_A     (   cls				,							_A				,							**_A		):







													'''simple docstring'''

													return tarfile.is_tarfile(_A		)






						@staticmethod
						def 	_A     (   _A				,							_A		):







													'''simple docstring'''

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

													__SCREAMING_SNAKE_CASE									= 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		):







													'''simple docstring'''

													os.makedirs(_A				,							exist_ok=_A		)
													__SCREAMING_SNAKE_CASE									= tarfile.open(_A		)
													tar_file.extractall(_A				,							members=TarExtractor.safemembers(_A				,							_A		)		)
													tar_file.close()







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			int      =  [B'''\x1F\x8B''']






						@staticmethod
						def 	_A     (   _A				,							_A		):







													'''simple docstring'''

													with gzip.open(_A				,							'rb'		) as gzip_file:
																				with open(_A				,							'wb'		) as extracted_file:
																											shutil.copyfileobj(_A				,							_A		)







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			Optional[int]      =  [
						    B'''PK\x03\x04''',
						    B'''PK\x05\x06''',  # empty archive
						    B'''PK\x07\x08''',  # spanned archive
						]






						@classmethod
						def 	_A     (   cls				,							_A				,							_A = b""		):







													'''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:
																											__SCREAMING_SNAKE_CASE									= _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:
																																																__SCREAMING_SNAKE_CASE									= fp.read(_A		)  # CD is where we expect it to be
																																																if len(_A		) == sizeCentralDir:
																																																							__SCREAMING_SNAKE_CASE									= 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		):







													'''simple docstring'''

													os.makedirs(_A				,							exist_ok=_A		)
													with zipfile.ZipFile(_A				,							'r'		) as zip_file:
																				zip_file.extractall(_A		)
																				zip_file.close()







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			int      =  [B'''\xFD\x37\x7A\x58\x5A\x00''']






						@staticmethod
						def 	_A     (   _A				,							_A		):







													'''simple docstring'''

													with lzma.open(_A		) as compressed_file:
																				with open(_A				,							'wb'		) as extracted_file:
																											shutil.copyfileobj(_A				,							_A		)







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			Any      =  [B'''Rar!\x1a\x07\x00''', B'''Rar!\x1a\x07\x01\x00''']  # RAR_ID  # RAR5_ID






						@staticmethod
						def 	_A     (   _A				,							_A		):







													'''simple docstring'''

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

													os.makedirs(_A				,							exist_ok=_A		)
													__SCREAMING_SNAKE_CASE									= rarfile.RarFile(_A		)
													rf.extractall(_A		)
													rf.close()







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			Dict      =  [B'''\x28\xb5\x2F\xFD''']






						@staticmethod
						def 	_A     (   _A				,							_A		):







													'''simple docstring'''

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

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







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			Union[str, Any]      =  [B'''\x42\x5A\x68''']






						@staticmethod
						def 	_A     (   _A				,							_A		):







													'''simple docstring'''

													with bza.open(_A				,							'rb'		) as compressed_file:
																				with open(_A				,							'wb'		) as extracted_file:
																											shutil.copyfileobj(_A				,							_A		)







class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			List[str]      =  [B'''\x37\x7A\xBC\xAF\x27\x1C''']






						@staticmethod
						def 	_A     (   _A				,							_A		):







													'''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        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						UpperCamelCase__      :			Optional[int]      =  [B'''\x04\x22\x4D\x18''']






						@staticmethod
						def 	_A     (   _A				,							_A		):







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

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







													'''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 	_A     (   _A				,							_A		):







													'''simple docstring'''

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






						@classmethod
						def 	_A     (   cls				,							_A				,							_A = False		):







													'''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				,							)
													__SCREAMING_SNAKE_CASE									= 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"/>







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= cls._get_magic_number_max_length()
													__SCREAMING_SNAKE_CASE									= 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"				,							):







													'''simple docstring'''

													os.makedirs(os.path.dirname(_A		)				,							exist_ok=_A		)
													# Prevent parallel extractions
													__SCREAMING_SNAKE_CASE									= 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				,							)
																																		__SCREAMING_SNAKE_CASE									= extractor if extractor != 'deprecated' else extractor_format
																											else:
																																		__SCREAMING_SNAKE_CASE									= 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 multiprocessing
from typing import TYPE_CHECKING, Optional, Union

from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream


if TYPE_CHECKING:
			import sqlitea

			import sqlalchemy

class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						def __init__(   self				,							_A				,							_A				,							_A = None				,							_A = None				,							_A = False				,							**_A				,							):







													'''simple docstring'''

													super().__init__(features=_A				,							cache_dir=_A				,							keep_in_memory=_A				,							**_A		)
													__SCREAMING_SNAKE_CASE									= Sql(
													    cache_dir=_A				,							features=_A				,							sql=_A				,							con=_A				,							**_A				,							)






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= None
													__SCREAMING_SNAKE_CASE									= None
													__SCREAMING_SNAKE_CASE									= None
													__SCREAMING_SNAKE_CASE									= None

													self.builder.download_and_prepare(
													    download_config=_A				,							download_mode=_A				,							verification_mode=_A				,							base_path=_A				,							)

													# Build dataset for splits
													__SCREAMING_SNAKE_CASE									= self.builder.as_dataset(
													    split='train'				,							verification_mode=_A				,							in_memory=self.keep_in_memory		)
													return dataset







class        UpperCAmelCase_  :

						'''simple docstring'''




						def __init__(   self				,							_A				,							_A				,							_A				,							_A = None				,							_A = None				,							**_A				,							):







													'''simple docstring'''

													if num_proc is not None and num_proc <= 0:
																				raise ValueError(f"""num_proc {num_proc} must be an integer > 0."""		)

													__SCREAMING_SNAKE_CASE									= dataset
													__SCREAMING_SNAKE_CASE									= name
													__SCREAMING_SNAKE_CASE									= con
													__SCREAMING_SNAKE_CASE									= batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
													__SCREAMING_SNAKE_CASE									= num_proc
													__SCREAMING_SNAKE_CASE									= to_sql_kwargs






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.to_sql_kwargs.pop('sql'				,							_A		)
													__SCREAMING_SNAKE_CASE									= self.to_sql_kwargs.pop('con'				,							_A		)
													__SCREAMING_SNAKE_CASE									= self.to_sql_kwargs.pop('index'				,							_A		)

													__SCREAMING_SNAKE_CASE									= self._write(index=_A				,							**self.to_sql_kwargs		)
													return written






						def 	_A     (   self				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= args
													__SCREAMING_SNAKE_CASE									= {**to_sql_kwargs, 'if_exists': 'append'} if offset > 0 else to_sql_kwargs
													__SCREAMING_SNAKE_CASE									= query_table(
													    table=self.dataset.data				,							key=slice(_A				,							offset + self.batch_size		)				,							indices=self.dataset._indices				,							)
													__SCREAMING_SNAKE_CASE									= batch.to_pandas()
													__SCREAMING_SNAKE_CASE									= df.to_sql(self.name				,							self.con				,							index=_A				,							**_A		)
													return num_rows or len(_A		)






						def 	_A     (   self				,							_A				,							**_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= 0

													if self.num_proc is None or self.num_proc == 1:
																				for offset in logging.tqdm(
																				    range(0				,							len(self.dataset		)				,							self.batch_size		)				,							unit='ba'				,							disable=not logging.is_progress_bar_enabled()				,							desc='Creating SQL from Arrow format'				,							):
																											written += self._batch_sql((offset, index, to_sql_kwargs)		)
													else:
																				__SCREAMING_SNAKE_CASE							,	__SCREAMING_SNAKE_CASE									= len(self.dataset		), self.batch_size
																				with multiprocessing.Pool(self.num_proc		) as pool:
																											for num_rows in logging.tqdm(
																											    pool.imap(
																											        self._batch_sql				,							[(offset, index, to_sql_kwargs) for offset in range(0				,							_A				,							_A		)]				,							)				,							total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size				,							unit='ba'				,							disable=not logging.is_progress_bar_enabled()				,							desc='Creating SQL from Arrow format'				,							):
																																		written += num_rows

													return written






