

from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase_             =     logging.get_logger(__name__)

lowercase_             =     {
    "SCUT-DLVCLab/lilt-roberta-en-base": (
        "https://huggingface.co/SCUT-DLVCLab/lilt-roberta-en-base/resolve/main/config.json"
    ),
}





class 				__lowerCAmelCase  (      UpperCAmelCase_							):
  _a		    =						"""lilt"""




  def __init__(       self							,     lowerCAmelCase=30_522							,     lowerCAmelCase=768							,     lowerCAmelCase=12							,     lowerCAmelCase=12							,     lowerCAmelCase=3_072							,     lowerCAmelCase="gelu"							,     lowerCAmelCase=0.1							,     lowerCAmelCase=0.1							,     lowerCAmelCase=512							,     lowerCAmelCase=2							,     lowerCAmelCase=0.02							,     lowerCAmelCase=1e-12							,     lowerCAmelCase=0							,     lowerCAmelCase="absolute"							,     lowerCAmelCase=None							,     lowerCAmelCase=4							,     lowerCAmelCase=1_024							,     **lowerCAmelCase							,     )						->				List[str]:
        '''simple docstring'''






        super().__init__(pad_token_id=_lowercase							,     **_lowercase      )

        _lowercase			 =vocab_size
        _lowercase			 =hidden_size
        _lowercase			 =num_hidden_layers
        _lowercase			 =num_attention_heads
        _lowercase			 =hidden_act
        _lowercase			 =intermediate_size
        _lowercase			 =hidden_dropout_prob
        _lowercase			 =attention_probs_dropout_prob
        _lowercase			 =max_position_embeddings
        _lowercase			 =type_vocab_size
        _lowercase			 =initializer_range
        _lowercase			 =layer_norm_eps
        _lowercase			 =position_embedding_type
        _lowercase			 =classifier_dropout
        _lowercase			 =channel_shrink_ratio
        _lowercase			 =max_ad_position_embeddings





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




  def __init__(       self							,     lowerCAmelCase = None      )						->				str:
        '''simple docstring'''






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




  def 						A__  (       self							,     lowerCAmelCase      )						->				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(lowerCAmelCase      )
        return os.path.join(self.extract_dir							,     hash_url_to_filename(lowerCAmelCase      )      )




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase      )						->				bool:
        '''simple docstring'''






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




  def 						A__  (       self							,     lowerCAmelCase							,     lowerCAmelCase = False      )						->				str:
        '''simple docstring'''






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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):




  @classmethod
  @abstractmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     **lowerCAmelCase      )						->				bool:
        '''simple docstring'''






        ...




  @staticmethod
  @abstractmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






        ...





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE    ,    SCREAMING_SNAKE_CASE							):
  _a		    =						[]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				List[Any]:
        '''simple docstring'''






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




  @classmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     lowerCAmelCase = b""      )						->				bool:
        '''simple docstring'''






        if not magic_number:
              _lowercase			 =max(len(lowerCAmelCase      ) for cls_magic_number in cls.magic_numbers      )
              try:
                    _lowercase			 =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 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):




  @classmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     **lowerCAmelCase      )						->				bool:
        '''simple docstring'''






        return tarfile.is_tarfile(lowerCAmelCase      )




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				List[Any]:
        '''simple docstring'''






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

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

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

        _lowercase			 =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 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\x1F\x8B"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[
      b"""PK\x03\x04""",
      b"""PK\x05\x06""",  # empty archive
      b"""PK\x07\x08""",  # spanned archive
  ]




  @classmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     lowerCAmelCase = b""      )						->				bool:
        '''simple docstring'''






        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:
                    _lowercase			 =_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:
                                      _lowercase			 =fp.read(lowerCAmelCase      )  # CD is where we expect it to be
                                      if len(lowerCAmelCase      ) == sizeCentralDir:
                                            _lowercase			 =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 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\xFD\x37\x7A\x58\x5A\x00"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""Rar!\x1a\x07\x00""", b"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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

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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\x28\xb5\x2F\xFD"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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

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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\x42\x5A\x68"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






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





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\x37\x7A\xBC\xAF\x27\x1C"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






        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 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  _a		    =						[b"""\x04\x22\x4D\x18"""]




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				None:
        '''simple docstring'''






        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 				__lowerCAmelCase  :
  #  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 						A__  (       cls      )						->				str:
        '''simple docstring'''






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




  @staticmethod
  def 						A__  (       lowerCAmelCase							,     lowerCAmelCase      )						->				Optional[Any]:
        '''simple docstring'''






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




  @classmethod
  def 						A__  (       cls							,     lowerCAmelCase							,     lowerCAmelCase = False      )						->				bool:
        '''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=lowerCAmelCase							,     )
        _lowercase			 =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 						A__  (       cls							,     lowerCAmelCase      )						->				str:  # <Added version="2.4.0"/>
        '''simple docstring'''






        _lowercase			 =cls._get_magic_number_max_length()
        _lowercase			 =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 						A__  (       cls							,     lowerCAmelCase							,     lowerCAmelCase							,     lowerCAmelCase = None							,     lowerCAmelCase = "deprecated"							,     )						->				None:
        '''simple docstring'''






        os.makedirs(os.path.dirname(lowerCAmelCase      )							,     exist_ok=lowerCAmelCase      )
        # Prevent parallel extractions
        _lowercase			 =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							,     )
                          _lowercase			 =extractor if extractor != 'deprecated' else extractor_format
                    else:
                          _lowercase			 =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      )


