


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


lowercase_	   =     get_logger(__name__)


class 	A_ :




      '''simple docstring'''


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




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




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




      def 					_snake_case     (    self:	Tuple						,				a:	str						,				a:	bool = False    ):
       __lowerCamelCase		:							Dict		 =						self.extractor.infer_extractor_format(a    )
       if not extractor_format:
        return input_path
       __lowerCamelCase		:							Dict		 =						self._get_output_path(a    )
       if self._do_extract(a						,				a    ):
        self.extractor.extract(a						,				a						,				a    )
       return output_path



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      @classmethod
      @abstractmethod
      def 					_snake_case     (    cls:	int						,				a:	Union[Path, str]						,				**a:	List[Any]    ):
       ...




      @staticmethod
      @abstractmethod
      def 					_snake_case     (    a:	Union[Path, str]						,				a:	Union[Path, str]    ):
       ...



class 	A_ (	__UpperCamelCase ,				__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       []




      @staticmethod
      def 					_snake_case     (    a:	Union[Path, str]						,				a:	int    ):
       with open(a						,				'rb'    ) as f:
        return f.read(a    )




      @classmethod
      def 					_snake_case     (    cls:	str						,				a:	Union[Path, str]						,				a:	bytes = b""    ):
       if not magic_number:
        __lowerCamelCase		:							Optional[Any]		 =						max(len(a    ) for cls_magic_number in cls.magic_numbers    )
        try:
         __lowerCamelCase		:							Tuple		 =						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 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      @classmethod
      def 					_snake_case     (    cls:	List[Any]						,				a:	Union[Path, str]						,				**a:	Tuple    ):
       return tarfile.is_tarfile(a    )




      @staticmethod
      def 					_snake_case     (    a:	Optional[int]						,				a:	int    ):

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

       __lowerCamelCase		:							Tuple		 =						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 					_snake_case     (    a:	Union[Path, str]						,				a:	Union[Path, str]    ):
       os.makedirs(a						,				exist_ok=a    )
       __lowerCamelCase		:							List[str]		 =						tarfile.open(a    )
       tar_file.extractall(a						,				members=TarExtractor.safemembers(a						,				a    )    )
       tar_file.close()



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       [B"""\x1F\x8B"""]




      @staticmethod
      def 					_snake_case     (    a:	Union[Path, str]						,				a:	Union[Path, str]    ):
       with gzip.open(a						,				'rb'    ) as gzip_file:
        with open(a						,				'wb'    ) as extracted_file:
         shutil.copyfileobj(a						,				a    )



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       [
          B"""PK\x03\x04""",
          B"""PK\x05\x06""",  # empty archive
          B"""PK\x07\x08""",  # spanned archive
      ]




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



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       [B"""\xFD\x37\x7A\x58\x5A\x00"""]




      @staticmethod
      def 					_snake_case     (    a:	Union[Path, str]						,				a:	Union[Path, str]    ):
       with lzma.open(a    ) as compressed_file:
        with open(a						,				'wb'    ) as extracted_file:
         shutil.copyfileobj(a						,				a    )



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       [B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID




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

       os.makedirs(a						,				exist_ok=a    )
       __lowerCamelCase		:							Tuple		 =						rarfile.RarFile(a    )
       rf.extractall(a    )
       rf.close()



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       [B"""\x28\xb5\x2F\xFD"""]




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

       __lowerCamelCase		:							Union[str, Any]		 =						zstd.ZstdDecompressor()
       with open(a						,				'rb'    ) as ifh, open(a						,				'wb'    ) as ofh:
        dctx.copy_stream(a						,				a    )



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       [B"""\x42\x5A\x68"""]




      @staticmethod
      def 					_snake_case     (    a:	Union[Path, str]						,				a:	Union[Path, str]    ):
       with bza.open(a						,				'rb'    ) as compressed_file:
        with open(a						,				'wb'    ) as extracted_file:
         shutil.copyfileobj(a						,				a    )



class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       [B"""\x37\x7A\xBC\xAF\x27\x1C"""]




      @staticmethod
      def 					_snake_case     (    a:	Union[Path, str]						,				a:	Union[Path, str]    ):
       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 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      __snake_case 	=       [B"""\x04\x22\x4D\x18"""]




      @staticmethod
      def 					_snake_case     (    a:	Union[Path, str]						,				a:	Union[Path, str]    ):
       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 	A_ :




      '''simple docstring'''


      __snake_case 	=       {
          "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 					_snake_case     (    cls:	Dict    ):
       return max(
           len(a    )
           for extractor in cls.extractors.values()
           if issubclass(a						,				a    )
           for extractor_magic_number in extractor.magic_numbers    )




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




      @classmethod
      def 					_snake_case     (    cls:	Tuple						,				a:	Union[Path, str]						,				a:	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=a						,				)
       __lowerCamelCase		:							List[str]		 =						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 					_snake_case     (    cls:	List[Any]						,				a:	Union[Path, str]    ):  # <Added version="2.4.0"/>
       __lowerCamelCase		:							Optional[int]		 =						cls._get_magic_number_max_length()
       __lowerCamelCase		:							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 					_snake_case     (    cls:	int						,				a:	Union[Path, str]						,				a:	Union[Path, str]						,				a:	Optional[str] = None						,				a:	Optional[BaseExtractor] = "deprecated"						,				):
       os.makedirs(os.path.dirname(a    )						,				exist_ok=a    )
       # Prevent parallel extractions
       __lowerCamelCase		:							Union[str, Any]		 =						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						,				)
          __lowerCamelCase		:							Dict		 =						extractor if extractor != 'deprecated' else extractor_format
         else:
          __lowerCamelCase		:							Union[str, Any]		 =						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 os
from typing import BinaryIO, Optional, Union

import numpy as np
import pyarrow.parquet as pq

from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config
from ..features.features import FeatureType, _visit
from ..formatting import query_table
from ..packaged_modules import _PACKAGED_DATASETS_MODULES
from ..packaged_modules.parquet.parquet import Parquet
from ..utils import logging
from ..utils.typing import NestedDataStructureLike, PathLike
from .abc import AbstractDatasetReader
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							List[str]		 =						np.inf

 def set_batch_size(SCREAMING_SNAKE_CASE__						) -> None:
  nonlocal batch_size
  if isinstance(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						):
   __lowerCamelCase		:							Union[str, Any]		 =						min(SCREAMING_SNAKE_CASE__      ,	config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS						)
  elif isinstance(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						):
   __lowerCamelCase		:							Optional[Any]		 =						min(SCREAMING_SNAKE_CASE__      ,	config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS						)
  elif isinstance(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						) and feature.dtype == "binary":
   __lowerCamelCase		:							List[str]		 =						min(SCREAMING_SNAKE_CASE__      ,	config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS						)

 _visit(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						)

 return None if batch_size is np.inf else batch_size


class 	A_ (	__UpperCamelCase   ):




      '''simple docstring'''


      def __init__(    self:	Tuple						,				a:	NestedDataStructureLike[PathLike]						,				a:	Optional[NamedSplit] = None						,				a:	Optional[Features] = None						,				a:	str = None						,				a:	bool = False						,				a:	bool = False						,				a:	Optional[int] = None						,				**a:	Optional[Any]						,				):
       super().__init__(
           a						,				split=a						,				features=a						,				cache_dir=a						,				keep_in_memory=a						,				streaming=a						,				num_proc=a						,				**a						,				)
       __lowerCamelCase		:							List[Any]		 =						path_or_paths if isinstance(a						,				a    ) else {self.split: path_or_paths}
       __lowerCamelCase		:							Optional[Any]		 =						_PACKAGED_DATASETS_MODULES['parquet'][1]
       __lowerCamelCase		:							List[str]		 =						Parquet(
           cache_dir=a						,				data_files=a						,				features=a						,				hash=a						,				**a						,				)




      def 					_snake_case     (    self:	List[str]    ):
       # Build iterable dataset
       if self.streaming:
        __lowerCamelCase		:							str		 =						self.builder.as_streaming_dataset(split=self.split    )
       # Build regular (map-style) dataset
       else:
        __lowerCamelCase		:							str		 =						None
        __lowerCamelCase		:							Optional[Any]		 =						None
        __lowerCamelCase		:							Union[str, Any]		 =						None
        __lowerCamelCase		:							int		 =						None

        self.builder.download_and_prepare(
            download_config=a						,				download_mode=a						,				verification_mode=a						,				base_path=a						,				num_proc=self.num_proc						,				)
        __lowerCamelCase		:							Tuple		 =						self.builder.as_dataset(
            split=self.split						,				verification_mode=a						,				in_memory=self.keep_in_memory    )
       return dataset



class 	A_ :




      '''simple docstring'''


      def __init__(    self:	Optional[int]						,				a:	Dataset						,				a:	Union[PathLike, BinaryIO]						,				a:	Optional[int] = None						,				**a:	List[Any]						,				):
       __lowerCamelCase		:							Optional[int]		 =						dataset
       __lowerCamelCase		:							List[Any]		 =						path_or_buf
       __lowerCamelCase		:							List[str]		 =						batch_size or get_writer_batch_size(dataset.features    )
       __lowerCamelCase		:							List[Any]		 =						parquet_writer_kwargs




      def 					_snake_case     (    self:	Union[str, Any]    ):
       __lowerCamelCase		:							Optional[int]		 =						self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE

       if isinstance(self.path_or_buf						,				(str, bytes, os.PathLike)    ):
        with open(self.path_or_buf						,				'wb+'    ) as buffer:
         __lowerCamelCase		:							Optional[int]		 =						self._write(file_obj=a						,				batch_size=a						,				**self.parquet_writer_kwargs    )
       else:
        __lowerCamelCase		:							Any		 =						self._write(file_obj=self.path_or_buf						,				batch_size=a						,				**self.parquet_writer_kwargs    )
       return written




      def 					_snake_case     (    self:	Optional[int]						,				a:	BinaryIO						,				a:	int						,				**a:	str    ):
       __lowerCamelCase		:							Dict		 =						0
       __lowerCamelCase		:							Union[str, Any]		 =						parquet_writer_kwargs.pop('path_or_buf'						,				a    )
       __lowerCamelCase		:							str		 =						self.dataset.features.arrow_schema

       __lowerCamelCase		:							Any		 =						pq.ParquetWriter(a						,				schema=a						,				**a    )

       for offset in logging.tqdm(
           range(0						,				len(self.dataset    )						,				a    )						,				unit='ba'						,				disable=not logging.is_progress_bar_enabled()						,				desc='Creating parquet from Arrow format'						,				):
        __lowerCamelCase		:							Any		 =						query_table(
            table=self.dataset._data						,				key=slice(a						,				offset + batch_size    )						,				indices=self.dataset._indices if self.dataset._indices is not None else None						,				)
        writer.write_table(a    )
        written += batch.nbytes
       writer.close()
       return written

