






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


_A	:			Any         =get_logger(__name__)

class _lowercase	:




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




							def 		lowerCamelCase_				(							self:				List[Any]			,							UpperCamelCase__:				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"
														lowerCamelCase__					:	int         =       os.path.abspath(UpperCamelCase__     )
														return os.path.join(self.extract_dir			,							hash_url_to_filename(UpperCamelCase__     )     )




							def 		lowerCamelCase_				(							self:				List[Any]			,							UpperCamelCase__:				str			,							UpperCamelCase__:				bool     ):
														return force_extract or (
														    not os.path.isfile(UpperCamelCase__     ) and not (os.path.isdir(UpperCamelCase__     ) and os.listdir(UpperCamelCase__     ))
														)




							def 		lowerCamelCase_				(							self:				Union[str, Any]			,							UpperCamelCase__:				str			,							UpperCamelCase__:				bool = False     ):
														lowerCamelCase__					:	Any         =       self.extractor.infer_extractor_format(UpperCamelCase__     )
														if not extractor_format:
																					return input_path
														lowerCamelCase__					:	str         =       self._get_output_path(UpperCamelCase__     )
														if self._do_extract(UpperCamelCase__			,							UpperCamelCase__     ):
																					self.extractor.extract(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__     )
														return output_path



class _lowercase	(				_lowercase		):




							@classmethod
							@abstractmethod
							def 		lowerCamelCase_				(							cls:				Tuple			,							UpperCamelCase__:				Union[Path, str]			,							**UpperCamelCase__:				int     ):
														...




							@staticmethod
							@abstractmethod
							def 		lowerCamelCase_				(							UpperCamelCase__:				Union[Path, str]			,							UpperCamelCase__:				Union[Path, str]     ):
														...



class _lowercase	(				_lowercase				,      _lowercase		):
							a				      =       []




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




							@classmethod
							def 		lowerCamelCase_				(							cls:				str			,							UpperCamelCase__:				Union[Path, str]			,							UpperCamelCase__:				bytes = b""     ):
														if not magic_number:
																					lowerCamelCase__					:	str         =       max(len(UpperCamelCase__     ) for cls_magic_number in cls.magic_numbers     )
																					try:
																												lowerCamelCase__					:	Optional[int]         =       cls.read_magic_number(UpperCamelCase__			,							UpperCamelCase__     )
																					except OSError:
																												return False
														return any(magic_number.startswith(UpperCamelCase__     ) for cls_magic_number in cls.magic_numbers     )



class _lowercase	(				_lowercase		):




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




							@staticmethod
							def 		lowerCamelCase_				(							UpperCamelCase__:				str			,							UpperCamelCase__:				int     ):

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

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

														def badlink(UpperCamelCase__:				int			,							UpperCamelCase__:				str     ) -> bool:
																					# Links are interpreted relative to the directory containing the link
																					lowerCamelCase__					:	Any         =       resolved(os.path.join(UpperCamelCase__			,							os.path.dirname(info.name     )     )     )
																					return badpath(info.linkname			,							base=UpperCamelCase__     )

														lowerCamelCase__					:	Union[str, Any]         =       resolved(UpperCamelCase__     )

														for finfo in members:
																					if badpath(finfo.name			,							UpperCamelCase__     ):
																												logger.error(F'''Extraction of {finfo.name} is blocked (illegal path)'''     )
																					elif finfo.issym() and badlink(UpperCamelCase__			,							UpperCamelCase__     ):
																												logger.error(F'''Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}'''     )
																					elif finfo.islnk() and badlink(UpperCamelCase__			,							UpperCamelCase__     ):
																												logger.error(F'''Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}'''     )
																					else:
																												yield finfo




							@staticmethod
							def 		lowerCamelCase_				(							UpperCamelCase__:				Union[Path, str]			,							UpperCamelCase__:				Union[Path, str]     ):
														os.makedirs(UpperCamelCase__			,							exist_ok=UpperCamelCase__     )
														lowerCamelCase__					:	Union[str, Any]         =       tarfile.open(UpperCamelCase__     )
														tar_file.extractall(UpperCamelCase__			,							members=TarExtractor.safemembers(UpperCamelCase__			,							UpperCamelCase__     )     )
														tar_file.close()



class _lowercase	(				_lowercase		):
							a				      =       [B"""\x1F\x8B"""]




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



class _lowercase	(				_lowercase		):
							a				      =       [
							    B"""PK\x03\x04""",
							    B"""PK\x05\x06""",  # empty archive
							    B"""PK\x07\x08""",  # spanned archive
							]




							@classmethod
							def 		lowerCamelCase_				(							cls:				Any			,							UpperCamelCase__:				Union[Path, str]			,							UpperCamelCase__:				bytes = b""     ):
														if super().is_extractable(UpperCamelCase__			,							magic_number=UpperCamelCase__     ):
																					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(UpperCamelCase__			,							"""rb"""     ) as fp:
																												lowerCamelCase__					:	Optional[Any]         =       _EndRecData(UpperCamelCase__     )
																												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:
																																																	lowerCamelCase__					:	Any         =       fp.read(UpperCamelCase__     )  # CD is where we expect it to be
																																																	if len(UpperCamelCase__     ) == sizeCentralDir:
																																																								lowerCamelCase__					:	Union[str, Any]         =       struct.unpack(UpperCamelCase__			,							UpperCamelCase__     )  # 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_				(							UpperCamelCase__:				Union[Path, str]			,							UpperCamelCase__:				Union[Path, str]     ):
														os.makedirs(UpperCamelCase__			,							exist_ok=UpperCamelCase__     )
														with zipfile.ZipFile(UpperCamelCase__			,							"""r"""     ) as zip_file:
																					zip_file.extractall(UpperCamelCase__     )
																					zip_file.close()



class _lowercase	(				_lowercase		):
							a				      =       [B"""\xFD\x37\x7A\x58\x5A\x00"""]




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



class _lowercase	(				_lowercase		):
							a				      =       [B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID




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

														os.makedirs(UpperCamelCase__			,							exist_ok=UpperCamelCase__     )
														lowerCamelCase__					:	str         =       rarfile.RarFile(UpperCamelCase__     )
														rf.extractall(UpperCamelCase__     )
														rf.close()



class _lowercase	(				_lowercase		):
							a				      =       [B"""\x28\xb5\x2F\xFD"""]




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

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



class _lowercase	(				_lowercase		):
							a				      =       [B"""\x42\x5A\x68"""]




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



class _lowercase	(				_lowercase		):
							a				      =       [B"""\x37\x7A\xBC\xAF\x27\x1C"""]




							@staticmethod
							def 		lowerCamelCase_				(							UpperCamelCase__:				Union[Path, str]			,							UpperCamelCase__:				Union[Path, str]     ):
														if not config.PY7ZR_AVAILABLE:
																					raise ImportError("""Please pip install py7zr"""     )
														import pyazr

														os.makedirs(UpperCamelCase__			,							exist_ok=UpperCamelCase__     )
														with pyazr.SevenZipFile(UpperCamelCase__			,							"""r"""     ) as archive:
																					archive.extractall(UpperCamelCase__     )



class _lowercase	(				_lowercase		):
							a				      =       [B"""\x04\x22\x4D\x18"""]




							@staticmethod
							def 		lowerCamelCase_				(							UpperCamelCase__:				Union[Path, str]			,							UpperCamelCase__:				Union[Path, str]     ):
														if not config.LZ4_AVAILABLE:
																					raise ImportError("""Please pip install lz4"""     )
														import lza.frame

														with lza.frame.open(UpperCamelCase__			,							"""rb"""     ) as compressed_file:
																					with open(UpperCamelCase__			,							"""wb"""     ) as extracted_file:
																												shutil.copyfileobj(UpperCamelCase__			,							UpperCamelCase__     )



class _lowercase	:
							#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
							a				      =       {
							    "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:				Tuple     ):
														return max(
														    len(UpperCamelCase__     )
														    for extractor in cls.extractors.values()
														    if issubclass(UpperCamelCase__			,							UpperCamelCase__     )
														    for extractor_magic_number in extractor.magic_numbers     )




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




							@classmethod
							def 		lowerCamelCase_				(							cls:				Optional[Any]			,							UpperCamelCase__:				Union[Path, str]			,							UpperCamelCase__:				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=UpperCamelCase__			,							)
														lowerCamelCase__					:	List[Any]         =       cls.infer_extractor_format(UpperCamelCase__     )
														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:				List[str]			,							UpperCamelCase__:				Union[Path, str]     ):  # <Added version="2.4.0"/>
														lowerCamelCase__					:	int         =       cls._get_magic_number_max_length()
														lowerCamelCase__					:	str         =       cls._read_magic_number(UpperCamelCase__			,							UpperCamelCase__     )
														for extractor_format, extractor in cls.extractors.items():
																					if extractor.is_extractable(UpperCamelCase__			,							magic_number=UpperCamelCase__     ):
																												return extractor_format




							@classmethod
							def 		lowerCamelCase_				(							cls:				List[str]			,							UpperCamelCase__:				Union[Path, str]			,							UpperCamelCase__:				Union[Path, str]			,							UpperCamelCase__:				Optional[str] = None			,							UpperCamelCase__:				Optional[BaseExtractor] = "deprecated"			,							):
														os.makedirs(os.path.dirname(UpperCamelCase__     )			,							exist_ok=UpperCamelCase__     )
														# Prevent parallel extractions
														lowerCamelCase__					:	Optional[Any]         =       str(Path(UpperCamelCase__     ).with_suffix(""".lock"""     )     )
														with FileLock(UpperCamelCase__     ):
																					shutil.rmtree(UpperCamelCase__			,							ignore_errors=UpperCamelCase__     )
																					if extractor_format or extractor != "deprecated":
																												if extractor != "deprecated" or not isinstance(UpperCamelCase__			,							UpperCamelCase__     ):  # 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=UpperCamelCase__			,							)
																																			lowerCamelCase__					:	int         =       extractor if extractor != """deprecated""" else extractor_format
																												else:
																																			lowerCamelCase__					:	Dict         =       cls.extractors[extractor_format]
																												return extractor.extract(UpperCamelCase__			,							UpperCamelCase__     )
																					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=UpperCamelCase__			,							)
																												for extractor in cls.extractors.values():
																																			if extractor.is_extractable(UpperCamelCase__     ):
																																										return extractor.extract(UpperCamelCase__			,							UpperCamelCase__     )


from unittest.mock import patch

import pyspark

from datasets.packaged_modules.spark.spark import (
    Spark,
    SparkExamplesIterable,
    _generate_iterable_examples,
)

from ..utils import (
    require_dill_gt_0_3_2,
    require_not_windows,
)






def  snake_case  (       snake_case__			:Union[str, Any]   ,	snake_case__			:Dict)						->   Any:
       _A        =  []
       for part_id in partition_order:
              _A        =  df.where(F'''SPARK_PARTITION_ID() = {part_id}''').collect()
              for row_idx, row in enumerate(snake_case__):
                     expected_row_ids_and_row_dicts.append((F'''{part_id}_{row_idx}''', row.asDict()))
       return expected_row_ids_and_row_dicts






@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   Optional[Any]:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(100).repartition(1)
       _A        =  Spark(snake_case__)
       # The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means
       # that each partition can hold 2 rows.
       spark_builder._repartition_df_if_needed(max_shard_size=16)
       # Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions.
       assert spark_builder.df.rdd.getNumPartitions() == 50






@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   Union[str, Any]:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(10).repartition(2)
       _A        =  [1, 0]
       _A        =  _generate_iterable_examples(snake_case__   ,	snake_case__)  # Reverse the partitions.
       _A        =  _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__   ,	snake_case__)

       for i, (row_id, row_dict) in enumerate(generate_fn()):
              _A   ,  _A        =  expected_row_ids_and_row_dicts[i]
              assert row_id == expected_row_id
              assert row_dict == expected_row_dict






@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   int:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(10).repartition(1)
       _A        =  SparkExamplesIterable(snake_case__)
       assert it.n_shards == 1
       for i, (row_id, row_dict) in enumerate(snake_case__):
              assert row_id == F'''0_{i}'''
              assert row_dict == {"id": i}






@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   Union[str, Any]:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(30).repartition(3)
       # Mock the generator so that shuffle reverses the partition indices.
       with patch("""numpy.random.Generator""") as generator_mock:
              _A        =  lambda snake_case__: x.reverse()
              _A        =  _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__   ,	[2, 1, 0])

              _A        =  SparkExamplesIterable(snake_case__).shuffle_data_sources(snake_case__)
              assert shuffled_it.n_shards == 3
              for i, (row_id, row_dict) in enumerate(snake_case__):
                     _A   ,  _A        =  expected_row_ids_and_row_dicts[i]
                     assert row_id == expected_row_id
                     assert row_dict == expected_row_dict






@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   List[str]:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(20).repartition(4)

       # Partitions 0 and 2
       _A        =  SparkExamplesIterable(snake_case__).shard_data_sources(worker_id=0   ,	num_workers=2)
       assert shard_it_a.n_shards == 2
       _A        =  _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__   ,	[0, 2])
       for i, (row_id, row_dict) in enumerate(snake_case__):
              _A   ,  _A        =  expected_row_ids_and_row_dicts_a[i]
              assert row_id == expected_row_id
              assert row_dict == expected_row_dict

       # Partitions 1 and 3
       _A        =  SparkExamplesIterable(snake_case__).shard_data_sources(worker_id=1   ,	num_workers=2)
       assert shard_it_a.n_shards == 2
       _A        =  _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__   ,	[1, 3])
       for i, (row_id, row_dict) in enumerate(snake_case__):
              _A   ,  _A        =  expected_row_ids_and_row_dicts_a[i]
              assert row_id == expected_row_id
              assert row_dict == expected_row_dict







@require_not_windows
@require_dill_gt_0_3_2
def  snake_case  (       )						->   Tuple:
       _A        =  pyspark.sql.SparkSession.builder.master("""local[*]""").appName("""pyspark""").getOrCreate()
       _A        =  spark.range(100).repartition(1)
       _A        =  Spark(snake_case__)
       # Choose a small max_shard_size for maximum partitioning.
       spark_builder._repartition_df_if_needed(max_shard_size=1)
       # The new number of partitions should not be greater than the number of rows.
       assert spark_builder.df.rdd.getNumPartitions() == 100




