




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_            =			get_logger(__name__)






class 			_lowerCAmelCase  :

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

      def 						__magic_name__( self   ,					__UpperCAmelCase		):
        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__					:	List[str]									=  os.path.abspath(__UpperCAmelCase		)
        return os.path.join(self.extract_dir   ,					hash_url_to_filename(__UpperCAmelCase		)		)

      def 						__magic_name__( self   ,					__UpperCAmelCase   ,					__UpperCAmelCase		):
        return force_extract or (
            not os.path.isfile(__UpperCAmelCase		) and not (os.path.isdir(__UpperCAmelCase		) and os.listdir(__UpperCAmelCase		))
        )







      def 						__magic_name__( self   ,					__UpperCAmelCase   ,					__UpperCAmelCase = False		):
        lowerCAmelCase__					:	Optional[Any]									=  self.extractor.infer_extractor_format(__UpperCAmelCase		)
        if not extractor_format:
          return input_path
        lowerCAmelCase__					:	Union[str, Any]									=  self._get_output_path(__UpperCAmelCase		)
        if self._do_extract(__UpperCAmelCase   ,					__UpperCAmelCase		):
          self.extractor.extract(__UpperCAmelCase   ,					__UpperCAmelCase   ,					__UpperCAmelCase		)
        return output_path






class 			_lowerCAmelCase  (	snake_case_						):

      @classmethod
      @abstractmethod
      def 						__magic_name__( cls   ,					__UpperCAmelCase   ,					**__UpperCAmelCase		):
        ...







      @staticmethod
      @abstractmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        ...






class 			_lowerCAmelCase  (	snake_case_     ,      snake_case_						):
      A__		  =		[]

      @staticmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        with open(__UpperCAmelCase   ,					'''rb'''		) as f:
          return f.read(__UpperCAmelCase		)







      @classmethod
      def 						__magic_name__( cls   ,					__UpperCAmelCase   ,					__UpperCAmelCase = b""		):
        if not magic_number:
          lowerCAmelCase__					:	Tuple									=  max(len(__UpperCAmelCase		) for cls_magic_number in cls.magic_numbers		)
          try:
            lowerCAmelCase__					:	List[Any]									=  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 			_lowerCAmelCase  (	snake_case_						):

      @classmethod
      def 						__magic_name__( cls   ,					__UpperCAmelCase   ,					**__UpperCAmelCase		):
        return tarfile.is_tarfile(__UpperCAmelCase		)

      @staticmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):

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

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

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

        lowerCAmelCase__					:	int									=  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 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        os.makedirs(__UpperCAmelCase   ,					exist_ok=__UpperCAmelCase		)
        lowerCAmelCase__					:	int									=  tarfile.open(__UpperCAmelCase		)
        tar_file.extractall(__UpperCAmelCase   ,					members=TarExtractor.safemembers(__UpperCAmelCase   ,					__UpperCAmelCase		)		)
        tar_file.close()






class 			_lowerCAmelCase  (	snake_case_						):
      A__		  =		[b'\x1F\x8B']

      @staticmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        with gzip.open(__UpperCAmelCase   ,					'''rb'''		) as gzip_file:
          with open(__UpperCAmelCase   ,					'''wb'''		) as extracted_file:
            shutil.copyfileobj(__UpperCAmelCase   ,					__UpperCAmelCase		)






class 			_lowerCAmelCase  (	snake_case_						):
      A__		  =		[
          b'PK\x03\x04',
          b'PK\x05\x06',  # empty archive
          b'PK\x07\x08',  # spanned archive
      ]

      @classmethod
      def 						__magic_name__( cls   ,					__UpperCAmelCase   ,					__UpperCAmelCase = 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__					:	List[str]									=  _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__					:	Dict									=  fp.read(__UpperCAmelCase		)  # CD is where we expect it to be
                  if len(__UpperCAmelCase		) == sizeCentralDir:
                    lowerCAmelCase__					:	Tuple									=  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 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        os.makedirs(__UpperCAmelCase   ,					exist_ok=__UpperCAmelCase		)
        with zipfile.ZipFile(__UpperCAmelCase   ,					'''r'''		) as zip_file:
          zip_file.extractall(__UpperCAmelCase		)
          zip_file.close()






class 			_lowerCAmelCase  (	snake_case_						):
      A__		  =		[b'\xFD\x37\x7A\x58\x5A\x00']

      @staticmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        with lzma.open(__UpperCAmelCase		) as compressed_file:
          with open(__UpperCAmelCase   ,					'''wb'''		) as extracted_file:
            shutil.copyfileobj(__UpperCAmelCase   ,					__UpperCAmelCase		)






class 			_lowerCAmelCase  (	snake_case_						):
      A__		  =		[b'Rar!\x1a\x07\x00', b'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID

      @staticmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        if not config.RARFILE_AVAILABLE:
          raise ImportError('''Please pip install rarfile'''		)
        import rarfile

        os.makedirs(__UpperCAmelCase   ,					exist_ok=__UpperCAmelCase		)
        lowerCAmelCase__					:	Tuple									=  rarfile.RarFile(__UpperCAmelCase		)
        rf.extractall(__UpperCAmelCase		)
        rf.close()






class 			_lowerCAmelCase  (	snake_case_						):
      A__		  =		[b'\x28\xb5\x2F\xFD']

      @staticmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        if not config.ZSTANDARD_AVAILABLE:
          raise ImportError('''Please pip install zstandard'''		)
        import zstandard as zstd

        lowerCAmelCase__					:	str									=  zstd.ZstdDecompressor()
        with open(__UpperCAmelCase   ,					'''rb'''		) as ifh, open(__UpperCAmelCase   ,					'''wb'''		) as ofh:
          dctx.copy_stream(__UpperCAmelCase   ,					__UpperCAmelCase		)






class 			_lowerCAmelCase  (	snake_case_						):
      A__		  =		[b'\x42\x5A\x68']

      @staticmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        with bza.open(__UpperCAmelCase   ,					'''rb'''		) as compressed_file:
          with open(__UpperCAmelCase   ,					'''wb'''		) as extracted_file:
            shutil.copyfileobj(__UpperCAmelCase   ,					__UpperCAmelCase		)






class 			_lowerCAmelCase  (	snake_case_						):
      A__		  =		[b'\x37\x7A\xBC\xAF\x27\x1C']

      @staticmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        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 			_lowerCAmelCase  (	snake_case_						):
      A__		  =		[b'\x04\x22\x4D\x18']

      @staticmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        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 			_lowerCAmelCase  :
      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 						__magic_name__( cls		):
        return max(
            len(__UpperCAmelCase		)
            for extractor in cls.extractors.values()
            if issubclass(__UpperCAmelCase   ,					__UpperCAmelCase		)
            for extractor_magic_number in extractor.magic_numbers		)

      @staticmethod
      def 						__magic_name__( __UpperCAmelCase   ,					__UpperCAmelCase		):
        try:
          return MagicNumberBaseExtractor.read_magic_number(__UpperCAmelCase   ,					magic_number_length=__UpperCAmelCase		)
        except OSError:
          return b""

      @classmethod
      def 						__magic_name__( cls   ,					__UpperCAmelCase   ,					__UpperCAmelCase = 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__					:	Optional[int]									=  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 						__magic_name__( cls   ,					__UpperCAmelCase		):  # <Added version="2.4.0"/>
        lowerCAmelCase__					:	Tuple									=  cls._get_magic_number_max_length()
        lowerCAmelCase__					:	Union[str, Any]									=  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 						__magic_name__( cls   ,					__UpperCAmelCase   ,					__UpperCAmelCase   ,					__UpperCAmelCase = None   ,					__UpperCAmelCase = "deprecated"   ,					):
        os.makedirs(os.path.dirname(__UpperCAmelCase		)   ,					exist_ok=__UpperCAmelCase		)
        # Prevent parallel extractions
        lowerCAmelCase__					:	str									=  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__					:	Any									=  extractor if extractor != '''deprecated''' else extractor_format
            else:
              lowerCAmelCase__					:	List[str]									=  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		)









import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
	from .tokenization_rembert import RemBertTokenizer
else:
	lowercase    				=   None

lowercase    				=   logging.get_logger(__name__)
lowercase    				=   {"vocab_file": "sentencepiece.model", "tokenizer_file": "tokenizer.json"}

lowercase    				=   {
    "vocab_file": {
        "google/rembert": "https://huggingface.co/google/rembert/resolve/main/sentencepiece.model",
    },
    "tokenizer_file": {
        "google/rembert": "https://huggingface.co/google/rembert/resolve/main/tokenizer.json",
    },
}

lowercase    				=   {
    "google/rembert": 256,
}

lowercase    				=   "▁"




class 					UpperCamelCase_ (     snake_case_							):



	'''simple docstring'''




	lowerCAmelCase						=					VOCAB_FILES_NAMES
	lowerCAmelCase						=					PRETRAINED_VOCAB_FILES_MAP
	lowerCAmelCase						=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	lowerCAmelCase						=					RemBertTokenizer




	def __init__(			self			,     a=None			,     a=None			,     a=True			,     a=True			,     a=False			,     a="[CLS]"			,     a="[SEP]"			,     a="<unk>"			,     a="[SEP]"			,     a="<pad>"			,     a="[CLS]"			,     a="[MASK]"			,     **a			,     )			->       Union[str, Any]:
								# Mask token behave like a normal word, i.e. include the space before it
								snake_case_           =				AddedToken(a			,     lstrip=a			,     rstrip=a   ) if isinstance(a			,     a   ) else mask_token

								super().__init__(
								    a			,     tokenizer_file=a			,     do_lower_case=a			,     remove_space=a			,     keep_accents=a			,     bos_token=a			,     eos_token=a			,     unk_token=a			,     sep_token=a			,     pad_token=a			,     cls_token=a			,     mask_token=a			,     **a			,     )

								snake_case_           =				do_lower_case
								snake_case_           =				remove_space
								snake_case_           =				keep_accents
								snake_case_           =				vocab_file
								snake_case_           =				False if not self.vocab_file else True




	def 				_UpperCamelCase     (			self			,     a			,     a = None   )			->       List[int]:
								snake_case_           =				[self.sep_token_id]
								snake_case_           =				[self.cls_token_id]
								if token_ids_a is None:
															return cls + token_ids_a + sep
								return cls + token_ids_a + sep + token_ids_a + sep




	def 				_UpperCamelCase     (			self			,     a			,     a = None			,     a = False   )			->       List[int]:

								if already_has_special_tokens:
															if token_ids_a is not None:
																						raise ValueError(
																						    'You should not supply a second sequence if the provided sequence of '
																						    'ids is already formatted with special tokens for the model.'   )
															return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

								if token_ids_a is not None:
															return [1] + ([0] * len(a   )) + [1] + ([0] * len(a   )) + [1]
								return [1] + ([0] * len(a   )) + [1]




	def 				_UpperCamelCase     (			self			,     a			,     a = None   )			->       List[int]:
								snake_case_           =				[self.sep_token_id]
								snake_case_           =				[self.cls_token_id]

								if token_ids_a is None:
															return len(cls + token_ids_a + sep   ) * [0]
								return len(cls + token_ids_a + sep   ) * [0] + len(token_ids_a + sep   ) * [1]






	def 				_UpperCamelCase     (			self			,     a			,     a = None   )			->       Tuple[str]:
								if not os.path.isdir(a   ):
															logger.error('Vocabulary path ({}) should be a directory'.format(a   )   )
															return
								snake_case_           =				os.path.join(
								    a			,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']   )

								if os.path.abspath(self.vocab_file   ) != os.path.abspath(a   ):
															copyfile(self.vocab_file			,     a   )

								return (out_vocab_file,)





