





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


_snake_case           =					get_logger(__name__)





class    lowerCAmelCase				:







  def __init__(     self    :List[Any]       ,				_lowercase    :Dict = None   ):






     '''simple docstring'''





     lowercase__					  =    (
         os.path.join(_lowercase       ,				config.EXTRACTED_DATASETS_DIR   ) if cache_dir else config.EXTRACTED_DATASETS_PATH
     )
     lowercase__					  =    Extractor







  def     UpperCAmelCase	(     self    :List[str]       ,				_lowercase    :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"
     lowercase__					  =    os.path.abspath(_lowercase   )
     return os.path.join(self.extract_dir       ,				hash_url_to_filename(_lowercase   )   )







  def     UpperCAmelCase	(     self    :int       ,				_lowercase    :int       ,				_lowercase    :List[Any]   ):






     '''simple docstring'''





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







  def     UpperCAmelCase	(     self    :List[Any]       ,				_lowercase    :Optional[Any]       ,				_lowercase    :Any = False   ):






     '''simple docstring'''





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





class    lowerCAmelCase				(  lowercase_   ):







  @classmethod
  @abstractmethod
  def     UpperCAmelCase	(     cls    :Any       ,				_lowercase    :str       ,				**_lowercase    :Dict   ):






     '''simple docstring'''





     ...







  @staticmethod
  @abstractmethod
  def     UpperCAmelCase	(     _lowercase    :Dict       ,				_lowercase    :List[str]   ):






     '''simple docstring'''





     ...





class    lowerCAmelCase				(  lowercase_				,				lowercase_   ):
  __lowerCamelCase						=     []







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :str       ,				_lowercase    :Any   ):






     '''simple docstring'''





     with open(_lowercase       ,				"rb"   ) as f:
        return f.read(_lowercase   )







  @classmethod
  def     UpperCAmelCase	(     cls    :Union[str, Any]       ,				_lowercase    :Tuple       ,				_lowercase    :Tuple = b""   ):






     '''simple docstring'''





     if not magic_number:
        lowercase__					  =    max(len(_lowercase   ) for cls_magic_number in cls.magic_numbers   )
        try:
           lowercase__					  =    cls.read_magic_number(_lowercase       ,				_lowercase   )
        except OSError:
           return False
     return any(magic_number.startswith(_lowercase   ) for cls_magic_number in cls.magic_numbers   )





class    lowerCAmelCase				(  lowercase_   ):







  @classmethod
  def     UpperCAmelCase	(     cls    :Optional[int]       ,				_lowercase    :Dict       ,				**_lowercase    :int   ):






     '''simple docstring'''





     return tarfile.is_tarfile(_lowercase   )







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :List[str]       ,				_lowercase    :Optional[Any]   ):






     '''simple docstring'''





     def resolved(_lowercase    :Union[str, Any]   ) -> str:
        return os.path.realpath(os.path.abspath(_lowercase   )   )

     def badpath(_lowercase    :Optional[int]       ,				_lowercase    :Union[str, Any]   ) -> bool:
        # joinpath will ignore base if path is absolute
        return not resolved(os.path.join(_lowercase       ,				_lowercase   )   ).startswith(_lowercase   )

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

     lowercase__					  =    resolved(_lowercase   )

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







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :List[Any]       ,				_lowercase    :Tuple   ):






     '''simple docstring'''





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





class    lowerCAmelCase				(  lowercase_   ):
  __lowerCamelCase						=     [b'\x1F\x8B']







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :List[Any]       ,				_lowercase    :Optional[Any]   ):






     '''simple docstring'''





     with gzip.open(_lowercase       ,				"rb"   ) as gzip_file:
        with open(_lowercase       ,				"wb"   ) as extracted_file:
           shutil.copyfileobj(_lowercase       ,				_lowercase   )





class    lowerCAmelCase				(  lowercase_   ):
  __lowerCamelCase						=     [
      b'PK\x03\x04',
      b'PK\x05\x06',  # empty archive
      b'PK\x07\x08',  # spanned archive
  ]







  @classmethod
  def     UpperCAmelCase	(     cls    :int       ,				_lowercase    :Tuple       ,				_lowercase    :List[Any] = b""   ):






     '''simple docstring'''





     if super().is_extractable(_lowercase       ,				magic_number=_lowercase   ):
        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(_lowercase       ,				"rb"   ) as fp:
           lowercase__					  =    _EndRecData(_lowercase   )
           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:
                    lowercase__					  =    fp.read(_lowercase   )  # CD is where we expect it to be
                    if len(_lowercase   ) == sizeCentralDir:
                       lowercase__					  =    struct.unpack(_lowercase       ,				_lowercase   )  # 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	(     _lowercase    :List[str]       ,				_lowercase    :List[Any]   ):






     '''simple docstring'''





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





class    lowerCAmelCase				(  lowercase_   ):
  __lowerCamelCase						=     [b'\xFD\x37\x7A\x58\x5A\x00']







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :str       ,				_lowercase    :Optional[int]   ):






     '''simple docstring'''





     with lzma.open(_lowercase   ) as compressed_file:
        with open(_lowercase       ,				"wb"   ) as extracted_file:
           shutil.copyfileobj(_lowercase       ,				_lowercase   )





class    lowerCAmelCase				(  lowercase_   ):
  __lowerCamelCase						=     [b'Rar!\x1a\x07\x00', b'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :Union[str, Any]       ,				_lowercase    :List[str]   ):






     '''simple docstring'''





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

     os.makedirs(_lowercase       ,				exist_ok=_lowercase   )
     lowercase__					  =    rarfile.RarFile(_lowercase   )
     rf.extractall(_lowercase   )
     rf.close()





class    lowerCAmelCase				(  lowercase_   ):
  __lowerCamelCase						=     [b'\x28\xb5\x2F\xFD']







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :Dict       ,				_lowercase    :str   ):






     '''simple docstring'''





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

     lowercase__					  =    zstd.ZstdDecompressor()
     with open(_lowercase       ,				"rb"   ) as ifh, open(_lowercase       ,				"wb"   ) as ofh:
        dctx.copy_stream(_lowercase       ,				_lowercase   )





class    lowerCAmelCase				(  lowercase_   ):
  __lowerCamelCase						=     [b'\x42\x5A\x68']







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :Tuple       ,				_lowercase    :Union[str, Any]   ):






     '''simple docstring'''





     with bza.open(_lowercase       ,				"rb"   ) as compressed_file:
        with open(_lowercase       ,				"wb"   ) as extracted_file:
           shutil.copyfileobj(_lowercase       ,				_lowercase   )





class    lowerCAmelCase				(  lowercase_   ):
  __lowerCamelCase						=     [b'\x37\x7A\xBC\xAF\x27\x1C']







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :int       ,				_lowercase    :Dict   ):






     '''simple docstring'''





     if not config.PY7ZR_AVAILABLE:
        raise ImportError("Please pip install py7zr"   )
     import pyazr

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





class    lowerCAmelCase				(  lowercase_   ):
  __lowerCamelCase						=     [b'\x04\x22\x4D\x18']







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :Optional[int]       ,				_lowercase    :int   ):






     '''simple docstring'''





     if not config.LZ4_AVAILABLE:
        raise ImportError("Please pip install lz4"   )
     import lza.frame

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





class    lowerCAmelCase				:
  __lowerCamelCase						=     {
      '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    :Dict   ):






     '''simple docstring'''





     return max(
         len(_lowercase   )
         for extractor in cls.extractors.values()
         if issubclass(_lowercase       ,				_lowercase   )
         for extractor_magic_number in extractor.magic_numbers   )







  @staticmethod
  def     UpperCAmelCase	(     _lowercase    :Union[str, Any]       ,				_lowercase    :Tuple   ):






     '''simple docstring'''





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







  @classmethod
  def     UpperCAmelCase	(     cls    :Union[str, Any]       ,				_lowercase    :int       ,				_lowercase    :Union[str, Any] = 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=_lowercase       ,				)
     lowercase__					  =    cls.infer_extractor_format(_lowercase   )
     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    :Optional[Any]       ,				_lowercase    :int   ):  # <Added version="2.4.0"/>






     '''simple docstring'''





     lowercase__					  =    cls._get_magic_number_max_length()
     lowercase__					  =    cls._read_magic_number(_lowercase       ,				_lowercase   )
     for extractor_format, extractor in cls.extractors.items():
        if extractor.is_extractable(_lowercase       ,				magic_number=_lowercase   ):
           return extractor_format







  @classmethod
  def     UpperCAmelCase	(     cls    :Union[str, Any]       ,				_lowercase    :List[Any]       ,				_lowercase    :Optional[Any]       ,				_lowercase    :Union[str, Any] = None       ,				_lowercase    :List[str] = "deprecated"       ,				):






     '''simple docstring'''





     os.makedirs(os.path.dirname(_lowercase   )       ,				exist_ok=_lowercase   )
     # Prevent parallel extractions
     lowercase__					  =    str(Path(_lowercase   ).with_suffix(".lock"   )   )
     with FileLock(_lowercase   ):
        shutil.rmtree(_lowercase       ,				ignore_errors=_lowercase   )
        if extractor_format or extractor != "deprecated":
           if extractor != "deprecated" or not isinstance(_lowercase       ,				_lowercase   ):  # 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=_lowercase       ,				)
              lowercase__					  =    extractor if extractor != "deprecated" else extractor_format
           else:
              lowercase__					  =    cls.extractors[extractor_format]
           return extractor.extract(_lowercase       ,				_lowercase   )
        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=_lowercase       ,				)
           for extractor in cls.extractors.values():
              if extractor.is_extractable(_lowercase   ):
                 return extractor.extract(_lowercase       ,				_lowercase   )










'''simple docstring'''


def 		_lowercase (SCREAMING_SNAKE_CASE							):




     '''simple docstring'''





     __A	:       List[str]      =							1
     __A	:       Union[str, Any]      =							2
     while i * i <= n:
          __A	:       List[Any]      =							0
          while n % i == 0:
               n //= i
               multiplicity += 1
          n_divisors *= multiplicity + 1
          i += 1
     if n > 1:
          n_divisors *= 2
     return n_divisors


def 		_lowercase ():




     '''simple docstring'''





     __A	:       Optional[Any]      =							1
     __A	:       Dict      =							1

     while True:
          i += 1
          t_num += i

          if count_divisors(SCREAMING_SNAKE_CASE							) > 500:
               break

     return t_num


if __name__ == "__main__":
      print(solution())

