






"""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


_lowerCAmelCase            =	get_logger(__name__)


class      UpperCamelCase		:






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






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






						def      __snake_case      (		self  :int			, __magic_name__  :str			, __magic_name__  :bool				)      ->bool:
										return force_extract or (
										    not os.path.isfile(__magic_name__				) and not (os.path.isdir(__magic_name__				) and os.listdir(__magic_name__				))
										)






						def      __snake_case      (		self  :Tuple			, __magic_name__  :str			, __magic_name__  :bool = False				)      ->str:
										lowercase    :      List[Any]       = self.extractor.infer_extractor_format(__magic_name__				)
										if not extractor_format:
														return input_path
										lowercase    :      Union[str, Any]       = self._get_output_path(__magic_name__				)
										if self._do_extract(__magic_name__			, __magic_name__				):
														self.extractor.extract(__magic_name__			, __magic_name__			, __magic_name__				)
										return output_path


class      UpperCamelCase		(__snake_case     ):






						@classmethod
						@abstractmethod
						def      __snake_case      (		cls  :Optional[Any]			, __magic_name__  :Union[Path, str]			, **__magic_name__  :str				)      ->bool:
										...






						@staticmethod
						@abstractmethod
						def      __snake_case      (		__magic_name__  :Union[Path, str]			, __magic_name__  :Union[Path, str]				)      ->None:
										...


class      UpperCamelCase		(__snake_case						,						__snake_case     ):
						_SCREAMING_SNAKE_CASE  : List[bytes]												=		[]






						@staticmethod
						def      __snake_case      (		__magic_name__  :Union[Path, str]			, __magic_name__  :int				)      ->int:
										with open(__magic_name__			, """rb"""				) as f:
														return f.read(__magic_name__				)






						@classmethod
						def      __snake_case      (		cls  :List[Any]			, __magic_name__  :Union[Path, str]			, __magic_name__  :bytes = b""				)      ->bool:
										if not magic_number:
														lowercase    :      Dict       = max(len(__magic_name__				) for cls_magic_number in cls.magic_numbers				)
														try:
																		lowercase    :      str       = cls.read_magic_number(__magic_name__			, __magic_name__				)
														except OSError:
																		return False
										return any(magic_number.startswith(__magic_name__				) for cls_magic_number in cls.magic_numbers				)


class      UpperCamelCase		(__snake_case     ):






						@classmethod
						def      __snake_case      (		cls  :Tuple			, __magic_name__  :Union[Path, str]			, **__magic_name__  :int				)      ->bool:
										return tarfile.is_tarfile(__magic_name__				)






						@staticmethod
						def      __snake_case      (		__magic_name__  :Optional[int]			, __magic_name__  :int				)      ->Union[str, Any]:

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

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

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

										lowercase    :      Optional[Any]       = resolved(__magic_name__				)

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






						@staticmethod
						def      __snake_case      (		__magic_name__  :Union[Path, str]			, __magic_name__  :Union[Path, str]				)      ->None:
										os.makedirs(__magic_name__			, exist_ok=__magic_name__				)
										lowercase    :      Any       = tarfile.open(__magic_name__				)
										tar_file.extractall(__magic_name__			, members=TarExtractor.safemembers(__magic_name__			, __magic_name__				)				)
										tar_file.close()


class      UpperCamelCase		(__snake_case     ):
						_SCREAMING_SNAKE_CASE  : Union[str, Any]												=		[b"""\x1F\x8B"""]






						@staticmethod
						def      __snake_case      (		__magic_name__  :Union[Path, str]			, __magic_name__  :Union[Path, str]				)      ->None:
										with gzip.open(__magic_name__			, """rb"""				) as gzip_file:
														with open(__magic_name__			, """wb"""				) as extracted_file:
																		shutil.copyfileobj(__magic_name__			, __magic_name__				)


class      UpperCamelCase		(__snake_case     ):
						_SCREAMING_SNAKE_CASE  : Tuple												=		[
						    b"""PK\x03\x04""",
						    b"""PK\x05\x06""",  # empty archive
						    b"""PK\x07\x08""",  # spanned archive
						]






						@classmethod
						def      __snake_case      (		cls  :List[Any]			, __magic_name__  :Union[Path, str]			, __magic_name__  :bytes = b""				)      ->bool:
										if super().is_extractable(__magic_name__			, magic_number=__magic_name__				):
														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(__magic_name__			, """rb"""				) as fp:
																		lowercase    :      str       = _EndRecData(__magic_name__				)
																		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    :      Optional[Any]       = fp.read(__magic_name__				)  # CD is where we expect it to be
																														if len(__magic_name__				) == sizeCentralDir:
																																		lowercase    :      int       = struct.unpack(__magic_name__			, __magic_name__				)  # 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      (		__magic_name__  :Union[Path, str]			, __magic_name__  :Union[Path, str]				)      ->None:
										os.makedirs(__magic_name__			, exist_ok=__magic_name__				)
										with zipfile.ZipFile(__magic_name__			, """r"""				) as zip_file:
														zip_file.extractall(__magic_name__				)
														zip_file.close()


class      UpperCamelCase		(__snake_case     ):
						_SCREAMING_SNAKE_CASE  : Any												=		[b"""\xFD\x37\x7A\x58\x5A\x00"""]






						@staticmethod
						def      __snake_case      (		__magic_name__  :Union[Path, str]			, __magic_name__  :Union[Path, str]				)      ->None:
										with lzma.open(__magic_name__				) as compressed_file:
														with open(__magic_name__			, """wb"""				) as extracted_file:
																		shutil.copyfileobj(__magic_name__			, __magic_name__				)


class      UpperCamelCase		(__snake_case     ):
						_SCREAMING_SNAKE_CASE  : Dict												=		[b"""Rar!\x1a\x07\x00""", b"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID






						@staticmethod
						def      __snake_case      (		__magic_name__  :Union[Path, str]			, __magic_name__  :Union[Path, str]				)      ->None:
										if not config.RARFILE_AVAILABLE:
														raise ImportError("""Please pip install rarfile"""				)
										import rarfile

										os.makedirs(__magic_name__			, exist_ok=__magic_name__				)
										lowercase    :      Optional[Any]       = rarfile.RarFile(__magic_name__				)
										rf.extractall(__magic_name__				)
										rf.close()


class      UpperCamelCase		(__snake_case     ):
						_SCREAMING_SNAKE_CASE  : int												=		[b"""\x28\xb5\x2F\xFD"""]






						@staticmethod
						def      __snake_case      (		__magic_name__  :Union[Path, str]			, __magic_name__  :Union[Path, str]				)      ->None:
										if not config.ZSTANDARD_AVAILABLE:
														raise ImportError("""Please pip install zstandard"""				)
										import zstandard as zstd

										lowercase    :      Any       = zstd.ZstdDecompressor()
										with open(__magic_name__			, """rb"""				) as ifh, open(__magic_name__			, """wb"""				) as ofh:
														dctx.copy_stream(__magic_name__			, __magic_name__				)


class      UpperCamelCase		(__snake_case     ):
						_SCREAMING_SNAKE_CASE  : Any												=		[b"""\x42\x5A\x68"""]






						@staticmethod
						def      __snake_case      (		__magic_name__  :Union[Path, str]			, __magic_name__  :Union[Path, str]				)      ->None:
										with bza.open(__magic_name__			, """rb"""				) as compressed_file:
														with open(__magic_name__			, """wb"""				) as extracted_file:
																		shutil.copyfileobj(__magic_name__			, __magic_name__				)


class      UpperCamelCase		(__snake_case     ):
						_SCREAMING_SNAKE_CASE  : Optional[int]												=		[b"""\x37\x7A\xBC\xAF\x27\x1C"""]






						@staticmethod
						def      __snake_case      (		__magic_name__  :Union[Path, str]			, __magic_name__  :Union[Path, str]				)      ->None:
										if not config.PY7ZR_AVAILABLE:
														raise ImportError("""Please pip install py7zr"""				)
										import pyazr

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


class      UpperCamelCase		(__snake_case     ):
						_SCREAMING_SNAKE_CASE  : Dict												=		[b"""\x04\x22\x4D\x18"""]






						@staticmethod
						def      __snake_case      (		__magic_name__  :Union[Path, str]			, __magic_name__  :Union[Path, str]				)      ->None:
										if not config.LZ4_AVAILABLE:
														raise ImportError("""Please pip install lz4"""				)
										import lza.frame

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


class      UpperCamelCase		:
						#  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
						_SCREAMING_SNAKE_CASE  : Dict[str, Type[BaseExtractor]]												=		{
						    "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  :Any				)      ->List[Any]:
										return max(
										    len(__magic_name__				)
										    for extractor in cls.extractors.values()
										    if issubclass(__magic_name__			, __magic_name__				)
										    for extractor_magic_number in extractor.magic_numbers				)






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






						@classmethod
						def      __snake_case      (		cls  :Optional[int]			, __magic_name__  :Union[Path, str]			, __magic_name__  :bool = 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=__magic_name__			, )
										lowercase    :      str       = cls.infer_extractor_format(__magic_name__				)
										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  :str			, __magic_name__  :Union[Path, str]				)      ->str:  # <Added version="2.4.0"/>
										lowercase    :      Tuple       = cls._get_magic_number_max_length()
										lowercase    :      List[str]       = cls._read_magic_number(__magic_name__			, __magic_name__				)
										for extractor_format, extractor in cls.extractors.items():
														if extractor.is_extractable(__magic_name__			, magic_number=__magic_name__				):
																		return extractor_format






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








"""simple docstring"""







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_fnet import FNetTokenizer
else:
				_lowerCAmelCase            =	None

_lowerCAmelCase            =	logging.get_logger(__name__)
_lowerCAmelCase            =	{'vocab_file': 'spiece.model', 'tokenizer_file': 'tokenizer.json'}

_lowerCAmelCase            =	{
    'vocab_file': {
        'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/spiece.model',
        'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/spiece.model',
    },
    'tokenizer_file': {
        'google/fnet-base': 'https://huggingface.co/google/fnet-base/resolve/main/tokenizer.json',
        'google/fnet-large': 'https://huggingface.co/google/fnet-large/resolve/main/tokenizer.json',
    },
}

_lowerCAmelCase            =	{
    'google/fnet-base': 5_12,
    'google/fnet-large': 5_12,
}

_lowerCAmelCase            =	'▁'


class      UpperCamelCase		(__snake_case     ):
						_SCREAMING_SNAKE_CASE  : Dict												=		VOCAB_FILES_NAMES
						_SCREAMING_SNAKE_CASE  : Optional[Any]												=		PRETRAINED_VOCAB_FILES_MAP
						_SCREAMING_SNAKE_CASE  : Optional[Any]												=		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						_SCREAMING_SNAKE_CASE  : Optional[Any]												=		["""input_ids""", """token_type_ids"""]
						_SCREAMING_SNAKE_CASE  : Union[str, Any]												=		FNetTokenizer






						def __init__(		self  :Optional[Any]			, __magic_name__  :Union[str, Any]=None			, __magic_name__  :Any=None			, __magic_name__  :List[str]=False			, __magic_name__  :Any=True			, __magic_name__  :Any=True			, __magic_name__  :Union[str, Any]="<unk>"			, __magic_name__  :List[Any]="[SEP]"			, __magic_name__  :Union[str, Any]="<pad>"			, __magic_name__  :Tuple="[CLS]"			, __magic_name__  :Optional[int]="[MASK]"			, **__magic_name__  :Optional[int]			, )      ->Tuple:
										# Mask token behave like a normal word, i.e. include the space before it and
										# is included in the raw text, there should be a match in a non-normalized sentence.
										lowercase    :      Union[str, Any]       = (
										    AddedToken(__magic_name__			, lstrip=__magic_name__			, rstrip=__magic_name__			, normalized=__magic_name__				)
										    if isinstance(__magic_name__			, __magic_name__				)
										    else mask_token
										)

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

										lowercase    :      Tuple       = do_lower_case
										lowercase    :      Tuple       = remove_space
										lowercase    :      List[str]       = keep_accents
										lowercase    :      Union[str, Any]       = vocab_file
										lowercase    :      int       = False if not self.vocab_file else True






						def      __snake_case      (		self  :Any			, __magic_name__  :List[int]			, __magic_name__  :Optional[List[int]] = None				)      ->List[int]:
										lowercase    :      List[str]       = [self.sep_token_id]
										lowercase    :      Any       = [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      __snake_case      (		self  :int			, __magic_name__  :List[int]			, __magic_name__  :Optional[List[int]] = None				)      ->List[int]:
										lowercase    :      Tuple       = [self.sep_token_id]
										lowercase    :      Union[str, Any]       = [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      __snake_case      (		self  :int			, __magic_name__  :str			, __magic_name__  :Optional[str] = None				)      ->Tuple[str]:
										if not os.path.isdir(__magic_name__				):
														logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""				)
														return
										lowercase    :      str       = os.path.join(
										    __magic_name__			, (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]				)

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

										return (out_vocab_file,)
