'''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: List[str]          =   get_logger(__name__)



class 			UpperCAmelCase  :





       '''simple docstring'''



       def __init__(						self	,   __lowerCAmelCase = None )  ->  Union[str, Any]:
        lowercase__				:    Optional[int]  =					(
            os.path.join(__lowerCAmelCase	,   config.EXTRACTED_DATASETS_DIR ) if cache_dir else config.EXTRACTED_DATASETS_PATH
        )
        lowercase__				:    Optional[Any]  =					Extractor

       def _lowerCAmelCase(						self	,   __lowerCAmelCase )  ->  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"
        lowercase__				:    Dict  =					os.path.abspath(__lowerCAmelCase )
        return os.path.join(self.extract_dir	,   hash_url_to_filename(__lowerCAmelCase ) )

       def _lowerCAmelCase(						self	,   __lowerCAmelCase	,   __lowerCAmelCase )  ->  bool:
        return force_extract or (
            not os.path.isfile(__lowerCAmelCase ) and not (os.path.isdir(__lowerCAmelCase ) and os.listdir(__lowerCAmelCase ))
        )


       def _lowerCAmelCase(						self	,   __lowerCAmelCase	,   __lowerCAmelCase = False )  ->  str:
        lowercase__				:    List[Any]  =					self.extractor.infer_extractor_format(__lowerCAmelCase )
        if not extractor_format:
         return input_path
        lowercase__				:    Optional[Any]  =					self._get_output_path(__lowerCAmelCase )
        if self._do_extract(__lowerCAmelCase	,   __lowerCAmelCase ):
         self.extractor.extract(__lowerCAmelCase	,   __lowerCAmelCase	,   __lowerCAmelCase )
        return output_path



class 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



       @classmethod
       @abstractmethod
       def _lowerCAmelCase(						cls	,   __lowerCAmelCase	,   **__lowerCAmelCase )  ->  bool:
        ...


       @staticmethod
       @abstractmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  None:
        ...



class 			UpperCAmelCase  (						a__    ,						a__					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    []

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  Dict:
        with open(__lowerCAmelCase	,   '''rb''' ) as f:
         return f.read(__lowerCAmelCase )


       @classmethod
       def _lowerCAmelCase(						cls	,   __lowerCAmelCase	,   __lowerCAmelCase = b"" )  ->  bool:
        if not magic_number:
         lowercase__				:    Optional[int]  =					max(len(__lowerCAmelCase ) for cls_magic_number in cls.magic_numbers )
         try:
          lowercase__				:    Optional[Any]  =					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 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



       @classmethod
       def _lowerCAmelCase(						cls	,   __lowerCAmelCase	,   **__lowerCAmelCase )  ->  bool:
        return tarfile.is_tarfile(__lowerCAmelCase )

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  Optional[int]:

        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__				:    List[Any]  =					resolved(os.path.join(__lowerCAmelCase	,   os.path.dirname(info.name ) ) )
         return badpath(info.linkname	,   base=__lowerCAmelCase )

        lowercase__				:    List[str]  =					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 _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  None:
        os.makedirs(__lowerCAmelCase	,   exist_ok=__lowerCAmelCase )
        lowercase__				:    List[str]  =					tarfile.open(__lowerCAmelCase )
        tar_file.extractall(__lowerCAmelCase	,   members=TarExtractor.safemembers(__lowerCAmelCase	,   __lowerCAmelCase ) )
        tar_file.close()



class 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    [b"\x1F\x8B"]

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  None:
        with gzip.open(__lowerCAmelCase	,   '''rb''' ) as gzip_file:
         with open(__lowerCAmelCase	,   '''wb''' ) as extracted_file:
          shutil.copyfileobj(__lowerCAmelCase	,   __lowerCAmelCase )



class 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



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

       @classmethod
       def _lowerCAmelCase(						cls	,   __lowerCAmelCase	,   __lowerCAmelCase = b"" )  ->  bool:
        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__				:    Any  =					_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__				:    Dict  =					fp.read(__lowerCAmelCase )  # CD is where we expect it to be
             if len(__lowerCAmelCase ) == sizeCentralDir:
              lowercase__				:    Any  =					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 _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  None:
        os.makedirs(__lowerCAmelCase	,   exist_ok=__lowerCAmelCase )
        with zipfile.ZipFile(__lowerCAmelCase	,   '''r''' ) as zip_file:
         zip_file.extractall(__lowerCAmelCase )
         zip_file.close()



class 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    [b"\xFD\x37\x7A\x58\x5A\x00"]

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  None:
        with lzma.open(__lowerCAmelCase ) as compressed_file:
         with open(__lowerCAmelCase	,   '''wb''' ) as extracted_file:
          shutil.copyfileobj(__lowerCAmelCase	,   __lowerCAmelCase )



class 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    [b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"]  # RAR_ID  # RAR5_ID

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  None:
        if not config.RARFILE_AVAILABLE:
         raise ImportError('''Please pip install rarfile''' )
        import rarfile

        os.makedirs(__lowerCAmelCase	,   exist_ok=__lowerCAmelCase )
        lowercase__				:    Dict  =					rarfile.RarFile(__lowerCAmelCase )
        rf.extractall(__lowerCAmelCase )
        rf.close()



class 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    [b"\x28\xb5\x2F\xFD"]

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  None:
        if not config.ZSTANDARD_AVAILABLE:
         raise ImportError('''Please pip install zstandard''' )
        import zstandard as zstd

        lowercase__				:    List[str]  =					zstd.ZstdDecompressor()
        with open(__lowerCAmelCase	,   '''rb''' ) as ifh, open(__lowerCAmelCase	,   '''wb''' ) as ofh:
         dctx.copy_stream(__lowerCAmelCase	,   __lowerCAmelCase )



class 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    [b"\x42\x5A\x68"]

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  None:
        with bza.open(__lowerCAmelCase	,   '''rb''' ) as compressed_file:
         with open(__lowerCAmelCase	,   '''wb''' ) as extracted_file:
          shutil.copyfileobj(__lowerCAmelCase	,   __lowerCAmelCase )



class 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    [b"\x37\x7A\xBC\xAF\x27\x1C"]

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  None:
        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 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    [b"\x04\x22\x4D\x18"]

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  None:
        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 			UpperCAmelCase  :





       '''simple docstring'''



       SCREAMING_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 _lowerCAmelCase(						cls )  ->  Optional[int]:
        return max(
            len(__lowerCAmelCase )
            for extractor in cls.extractors.values()
            if issubclass(__lowerCAmelCase	,   __lowerCAmelCase )
            for extractor_magic_number in extractor.magic_numbers )

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase )  ->  Union[str, Any]:
        try:
         return MagicNumberBaseExtractor.read_magic_number(__lowerCAmelCase	,   magic_number_length=__lowerCAmelCase )
        except OSError:
         return b""

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


'''simple docstring'''

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

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


if is_sentencepiece_available():
  from .tokenization_ta import TaTokenizer
else:
  __a: Tuple          =   None


__a: Tuple          =   logging.get_logger(__name__)

__a: Optional[Any]          =   {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""}

__a: Optional[Any]          =   {
    """vocab_file""": {
        """t5-small""": """https://huggingface.co/t5-small/resolve/main/spiece.model""",
        """t5-base""": """https://huggingface.co/t5-base/resolve/main/spiece.model""",
        """t5-large""": """https://huggingface.co/t5-large/resolve/main/spiece.model""",
        """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/spiece.model""",
        """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/spiece.model""",
    },
    """tokenizer_file""": {
        """t5-small""": """https://huggingface.co/t5-small/resolve/main/tokenizer.json""",
        """t5-base""": """https://huggingface.co/t5-base/resolve/main/tokenizer.json""",
        """t5-large""": """https://huggingface.co/t5-large/resolve/main/tokenizer.json""",
        """t5-3b""": """https://huggingface.co/t5-3b/resolve/main/tokenizer.json""",
        """t5-11b""": """https://huggingface.co/t5-11b/resolve/main/tokenizer.json""",
    },
}


# TODO(PVP) - this should be removed in Transformers v5
__a: Tuple          =   {
    """t5-small""": 5_12,
    """t5-base""": 5_12,
    """t5-large""": 5_12,
    """t5-3b""": 5_12,
    """t5-11b""": 5_12,
}



class 			UpperCAmelCase  (						a__					):





       '''simple docstring'''



       SCREAMING_SNAKE_CASE							=    VOCAB_FILES_NAMES
       SCREAMING_SNAKE_CASE							=    PRETRAINED_VOCAB_FILES_MAP
       SCREAMING_SNAKE_CASE							=    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       SCREAMING_SNAKE_CASE							=    ["input_ids", "attention_mask"]
       SCREAMING_SNAKE_CASE							=    TaTokenizer

       SCREAMING_SNAKE_CASE							=    []

       def __init__(						self	,   __lowerCAmelCase=None	,   __lowerCAmelCase=None	,   __lowerCAmelCase="</s>"	,   __lowerCAmelCase="<unk>"	,   __lowerCAmelCase="<pad>"	,   __lowerCAmelCase=100	,   __lowerCAmelCase=None	,   **__lowerCAmelCase	,   )  ->  Union[str, Any]:
        # Add extra_ids to the special token list
        if extra_ids > 0 and additional_special_tokens is None:
         lowercase__				:    Union[str, Any]  =					[F"""<extra_id_{i}>""" for i in range(__lowerCAmelCase )]
        elif extra_ids > 0 and additional_special_tokens is not None:
         # Check that we have the right number of extra special tokens
         lowercase__				:    Dict  =					len(set(filter(lambda __lowerCAmelCase : bool('''extra_id_''' in str(__lowerCAmelCase ) )	,   __lowerCAmelCase ) ) )
         if extra_tokens != extra_ids:
          raise ValueError(
              F"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"""
              ''' provided to T5Tokenizer. In this case the additional_special_tokens must include the extra_ids'''
              ''' tokens''' )

        super().__init__(
            __lowerCAmelCase	,   tokenizer_file=__lowerCAmelCase	,   eos_token=__lowerCAmelCase	,   unk_token=__lowerCAmelCase	,   pad_token=__lowerCAmelCase	,   extra_ids=__lowerCAmelCase	,   additional_special_tokens=__lowerCAmelCase	,   **__lowerCAmelCase	,   )

        lowercase__				:    Union[str, Any]  =					vocab_file
        lowercase__				:    Optional[int]  =					False if not self.vocab_file else True
        lowercase__				:    Any  =					extra_ids

       @staticmethod
       def _lowerCAmelCase(						__lowerCAmelCase	,   __lowerCAmelCase	,   __lowerCAmelCase )  ->  Union[str, Any]:
        if pretrained_model_name_or_path in TaTokenizerFast.max_model_input_sizes:
         lowercase__				:    Any  =					TaTokenizerFast.max_model_input_sizes[pretrained_model_name_or_path]
         if init_max_model_length is not None and init_max_model_length != max_model_length:
          return init_max_model_length
         elif init_max_model_length is None:
          warnings.warn(
              '''This tokenizer was incorrectly instantiated with a model max length of'''
              F""" {deprecated_max_model_length} which will be corrected in Transformers v5.\nFor now, this"""
              ''' behavior is kept to avoid breaking backwards compatibility when padding/encoding with'''
              ''' `truncation is True`.\n- Be aware that you SHOULD NOT rely on'''
              F""" {pretrained_model_name_or_path} automatically truncating your input to"""
              F""" {deprecated_max_model_length} when padding/encoding.\n- If you want to encode/pad to sequences"""
              F""" longer than {deprecated_max_model_length} you can either instantiate this tokenizer with"""
              ''' `model_max_length` or pass `max_length` when encoding/padding.\n- To avoid this warning, please'''
              ''' instantiate this tokenizer with `model_max_length` set to your preferred value.'''	,   __lowerCAmelCase	,   )

        return max_model_length

       def _lowerCAmelCase(						self	,   __lowerCAmelCase	,   __lowerCAmelCase = None )  ->  Tuple[str]:
        if not self.can_save_slow_tokenizer:
         raise ValueError(
             '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '''
             '''tokenizer.''' )

        if not os.path.isdir(__lowerCAmelCase ):
         logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" )
         return
        lowercase__				:    List[Any]  =					os.path.join(
            __lowerCAmelCase	,   (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file'''] )

        if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCAmelCase ):
         copyfile(self.vocab_file	,   __lowerCAmelCase )
         logger.info(F"""Copy vocab file to {out_vocab_file}""" )

        return (out_vocab_file,)

       def _lowerCAmelCase(						self	,   __lowerCAmelCase	,   __lowerCAmelCase = None )  ->  List[int]:
        lowercase__				:    Any  =					token_ids_a + [self.eos_token_id]
        if token_ids_a is None:
         return self.prefix_tokens + token_ids_a
        else:
         lowercase__				:    Dict  =					token_ids_a + [self.eos_token_id]
         return self.prefix_tokens + token_ids_a + token_ids_a

       def _lowerCAmelCase(						self	,   __lowerCAmelCase	,   __lowerCAmelCase = None )  ->  List[int]:
        lowercase__				:    Optional[int]  =					[self.eos_token_id]

        if token_ids_a is None:
         return len(token_ids_a + eos ) * [0]
        return len(token_ids_a + eos + token_ids_a + eos ) * [0]

       def _lowerCAmelCase(						self )  ->  List[Any]:
        return list(
            set(filter(lambda __lowerCAmelCase : bool(re.search(r'''<extra_id_\d+>'''	,   __lowerCAmelCase ) ) is not None	,   self.additional_special_tokens ) ) )


       def _lowerCAmelCase(						self )  ->  Tuple:
        return [self.convert_tokens_to_ids(__lowerCAmelCase ) for token in self.get_sentinel_tokens()]

