





'''simple docstring'''






import json
import os
from functools import lru_cache
from typing import List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


__lowerCamelCase						: int		=   logging.get_logger(__name__)


__lowerCamelCase						: Optional[int]		=   {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt'}

__lowerCamelCase						: str		=   {
    'vocab_file': {
        'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/vocab.json',
        'allenai/longformer-large-4096': (
            'https://huggingface.co/allenai/longformer-large-4096/resolve/main/vocab.json'
        ),
        'allenai/longformer-large-4096-finetuned-triviaqa': (
            'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/vocab.json'
        ),
        'allenai/longformer-base-4096-extra.pos.embd.only': (
            'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/vocab.json'
        ),
        'allenai/longformer-large-4096-extra.pos.embd.only': (
            'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/vocab.json'
        ),
    },
    'merges_file': {
        'allenai/longformer-base-4096': 'https://huggingface.co/allenai/longformer-base-4096/resolve/main/merges.txt',
        'allenai/longformer-large-4096': (
            'https://huggingface.co/allenai/longformer-large-4096/resolve/main/merges.txt'
        ),
        'allenai/longformer-large-4096-finetuned-triviaqa': (
            'https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/merges.txt'
        ),
        'allenai/longformer-base-4096-extra.pos.embd.only': (
            'https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/merges.txt'
        ),
        'allenai/longformer-large-4096-extra.pos.embd.only': (
            'https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/merges.txt'
        ),
    },
}

__lowerCamelCase						: Optional[Any]		=   {
    'allenai/longformer-base-4096': 4096,
    'allenai/longformer-large-4096': 4096,
    'allenai/longformer-large-4096-finetuned-triviaqa': 4096,
    'allenai/longformer-base-4096-extra.pos.embd.only': 4096,
    'allenai/longformer-large-4096-extra.pos.embd.only': 4096,
}


@lru_cache()
# Copied from transformers.models.roberta.tokenization_roberta.bytes_to_unicode
def 					_a   ():


  """simple docstring"""

  _UpperCamelCase       			=(
      list(range(ord('''!'''   )  ,      ord('''~'''   ) + 1   )   ) + list(range(ord('''¡'''   )  ,      ord('''¬'''   ) + 1   )   ) + list(range(ord('''®'''   )  ,      ord('''ÿ'''   ) + 1   )   )
  )
  _UpperCamelCase       			=bs[:]
  _UpperCamelCase       			=0
  for b in range(2**8   ):
    if b not in bs:
      bs.append(__SCREAMING_SNAKE_CASE   )
      cs.append(2**8 + n   )
      n += 1
  _UpperCamelCase       			=[chr(__SCREAMING_SNAKE_CASE   ) for n in cs]
  return dict(zip(__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   )   )


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  _UpperCamelCase       			=set()
  _UpperCamelCase       			=word[0]
  for char in word[1:]:
    pairs.add((prev_char, char)   )
    _UpperCamelCase       			=char
  return pairs







class 		UpperCAmelCase   (				lowercase_):


  """simple docstring"""







  lowerCAmelCase_					=				VOCAB_FILES_NAMES
  lowerCAmelCase_					=				PRETRAINED_VOCAB_FILES_MAP
  lowerCAmelCase_					=				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  lowerCAmelCase_					=				["""input_ids""", """attention_mask"""]


  def __init__(				self    :					Optional[int]							,	UpperCamelCase__    :					List[str]							,	UpperCamelCase__    :					Optional[Any]							,	UpperCamelCase__    :					List[str]="replace"							,	UpperCamelCase__    :					Union[str, Any]="<s>"							,	UpperCamelCase__    :					Dict="</s>"							,	UpperCamelCase__    :					Optional[int]="</s>"							,	UpperCamelCase__    :					Tuple="<s>"							,	UpperCamelCase__    :					Union[str, Any]="<unk>"							,	UpperCamelCase__    :					Dict="<pad>"							,	UpperCamelCase__    :					Tuple="<mask>"							,	UpperCamelCase__    :					List[str]=False							,	**UpperCamelCase__    :					str							,	)     ->						List[str]:
    _UpperCamelCase       			=AddedToken(UpperCamelCase__							,	lstrip=UpperCamelCase__							,	rstrip=UpperCamelCase__  ) if isinstance(UpperCamelCase__							,	UpperCamelCase__  ) else bos_token
    _UpperCamelCase       			=AddedToken(UpperCamelCase__							,	lstrip=UpperCamelCase__							,	rstrip=UpperCamelCase__  ) if isinstance(UpperCamelCase__							,	UpperCamelCase__  ) else eos_token
    _UpperCamelCase       			=AddedToken(UpperCamelCase__							,	lstrip=UpperCamelCase__							,	rstrip=UpperCamelCase__  ) if isinstance(UpperCamelCase__							,	UpperCamelCase__  ) else sep_token
    _UpperCamelCase       			=AddedToken(UpperCamelCase__							,	lstrip=UpperCamelCase__							,	rstrip=UpperCamelCase__  ) if isinstance(UpperCamelCase__							,	UpperCamelCase__  ) else cls_token
    _UpperCamelCase       			=AddedToken(UpperCamelCase__							,	lstrip=UpperCamelCase__							,	rstrip=UpperCamelCase__  ) if isinstance(UpperCamelCase__							,	UpperCamelCase__  ) else unk_token
    _UpperCamelCase       			=AddedToken(UpperCamelCase__							,	lstrip=UpperCamelCase__							,	rstrip=UpperCamelCase__  ) if isinstance(UpperCamelCase__							,	UpperCamelCase__  ) else pad_token

    # Mask token behave like a normal word, i.e. include the space before it
    _UpperCamelCase       			=AddedToken(UpperCamelCase__							,	lstrip=UpperCamelCase__							,	rstrip=UpperCamelCase__  ) if isinstance(UpperCamelCase__							,	UpperCamelCase__  ) else mask_token

    super().__init__(
        errors=UpperCamelCase__							,	bos_token=UpperCamelCase__							,	eos_token=UpperCamelCase__							,	unk_token=UpperCamelCase__							,	sep_token=UpperCamelCase__							,	cls_token=UpperCamelCase__							,	pad_token=UpperCamelCase__							,	mask_token=UpperCamelCase__							,	add_prefix_space=UpperCamelCase__							,	**UpperCamelCase__							,	)

    with open(UpperCamelCase__							,	encoding='''utf-8'''  ) as vocab_handle:
      _UpperCamelCase       			=json.load(UpperCamelCase__  )
    _UpperCamelCase       			={v: k for k, v in self.encoder.items()}
    _UpperCamelCase       			=errors  # how to handle errors in decoding
    _UpperCamelCase       			=bytes_to_unicode()
    _UpperCamelCase       			={v: k for k, v in self.byte_encoder.items()}
    with open(UpperCamelCase__							,	encoding='''utf-8'''  ) as merges_handle:
      _UpperCamelCase       			=merges_handle.read().split('''\n'''  )[1:-1]
    _UpperCamelCase       			=[tuple(merge.split()  ) for merge in bpe_merges]
    _UpperCamelCase       			=dict(zip(UpperCamelCase__							,	range(len(UpperCamelCase__  )  )  )  )
    _UpperCamelCase       			={}
    _UpperCamelCase       			=add_prefix_space

    # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
    _UpperCamelCase       			=re.compile(R'''\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+'''  )


  @property
  def   UpperCamelCase__      (				self    :					Optional[Any]  )     ->						Union[str, Any]:
    return len(self.encoder  )


  def   UpperCamelCase__      (				self    :					Optional[Any]  )     ->						Any:
    return dict(self.encoder							,	**self.added_tokens_encoder  )


  def   UpperCamelCase__      (				self    :					int							,	UpperCamelCase__    :					Any  )     ->						Optional[int]:
    if token in self.cache:
      return self.cache[token]
    _UpperCamelCase       			=tuple(UpperCamelCase__  )
    _UpperCamelCase       			=get_pairs(UpperCamelCase__  )

    if not pairs:
      return token

    while True:
      _UpperCamelCase       			=min(UpperCamelCase__							,	key=lambda UpperCamelCase__  : self.bpe_ranks.get(UpperCamelCase__							,	float('''inf'''  )  )  )
      if bigram not in self.bpe_ranks:
        break
      _UpperCamelCase			,     _UpperCamelCase       			=bigram
      _UpperCamelCase       			=[]
      _UpperCamelCase       			=0
      while i < len(UpperCamelCase__  ):
        try:
          _UpperCamelCase       			=word.index(UpperCamelCase__							,	UpperCamelCase__  )
        except ValueError:
          new_word.extend(word[i:]  )
          break
        else:
          new_word.extend(word[i:j]  )
          _UpperCamelCase       			=j

        if word[i] == first and i < len(UpperCamelCase__  ) - 1 and word[i + 1] == second:
          new_word.append(first + second  )
          i += 2
        else:
          new_word.append(word[i]  )
          i += 1
      _UpperCamelCase       			=tuple(UpperCamelCase__  )
      _UpperCamelCase       			=new_word
      if len(UpperCamelCase__  ) == 1:
        break
      else:
        _UpperCamelCase       			=get_pairs(UpperCamelCase__  )
    _UpperCamelCase       			=''' '''.join(UpperCamelCase__  )
    _UpperCamelCase       			=word
    return word


  def   UpperCamelCase__      (				self    :					Union[str, Any]							,	UpperCamelCase__    :					str  )     ->						Any:
    _UpperCamelCase       			=[]
    for token in re.findall(self.pat							,	UpperCamelCase__  ):
      _UpperCamelCase       			=''''''.join(
          self.byte_encoder[b] for b in token.encode('''utf-8'''  )  )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
      bpe_tokens.extend(bpe_token for bpe_token in self.bpe(UpperCamelCase__  ).split(''' '''  )  )
    return bpe_tokens


  def   UpperCamelCase__      (				self    :					Dict							,	UpperCamelCase__    :					str  )     ->						List[Any]:
    return self.encoder.get(UpperCamelCase__							,	self.encoder.get(self.unk_token  )  )


  def   UpperCamelCase__      (				self    :					str							,	UpperCamelCase__    :					int  )     ->						Dict:
    return self.decoder.get(UpperCamelCase__  )


  def   UpperCamelCase__      (				self    :					List[str]							,	UpperCamelCase__    :					List[str]  )     ->						Optional[Any]:
    _UpperCamelCase       			=''''''.join(UpperCamelCase__  )
    _UpperCamelCase       			=bytearray([self.byte_decoder[c] for c in text]  ).decode('''utf-8'''							,	errors=self.errors  )
    return text


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

    with open(UpperCamelCase__							,	'''w'''							,	encoding='''utf-8'''  ) as f:
      f.write(json.dumps(self.encoder							,	indent=2							,	sort_keys=UpperCamelCase__							,	ensure_ascii=UpperCamelCase__  ) + '''\n'''  )

    _UpperCamelCase       			=0
    with open(UpperCamelCase__							,	'''w'''							,	encoding='''utf-8'''  ) as writer:
      writer.write('''#version: 0.2\n'''  )
      for bpe_tokens, token_index in sorted(self.bpe_ranks.items()							,	key=lambda UpperCamelCase__  : kv[1]  ):
        if index != token_index:
          logger.warning(
              F'''Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'''
              ''' Please check that the tokenizer is not corrupted!'''  )
          _UpperCamelCase       			=token_index
        writer.write(''' '''.join(UpperCamelCase__  ) + '''\n'''  )
        index += 1

    return vocab_file, merge_file


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


  def   UpperCamelCase__      (				self    :					Any							,	UpperCamelCase__    :					List[int]							,	UpperCamelCase__    :					Optional[List[int]] = None							,	UpperCamelCase__    :					bool = False  )     ->						List[int]:
    if already_has_special_tokens:
      return super().get_special_tokens_mask(
          token_ids_a=UpperCamelCase__							,	token_ids_a=UpperCamelCase__							,	already_has_special_tokens=UpperCamelCase__  )

    if token_ids_a is None:
      return [1] + ([0] * len(UpperCamelCase__  )) + [1]
    return [1] + ([0] * len(UpperCamelCase__  )) + [1, 1] + ([0] * len(UpperCamelCase__  )) + [1]


  def   UpperCamelCase__      (				self    :					List[Any]							,	UpperCamelCase__    :					List[int]							,	UpperCamelCase__    :					Optional[List[int]] = None  )     ->						List[int]:
    _UpperCamelCase       			=[self.sep_token_id]
    _UpperCamelCase       			=[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 + sep + token_ids_a + sep  ) * [0]




  def   UpperCamelCase__      (				self    :					Dict							,	UpperCamelCase__    :					List[Any]							,	UpperCamelCase__    :					List[Any]=False							,	**UpperCamelCase__    :					Optional[Any]  )     ->						List[Any]:
    _UpperCamelCase       			=kwargs.pop('''add_prefix_space'''							,	self.add_prefix_space  )
    if (is_split_into_words or add_prefix_space) and (len(UpperCamelCase__  ) > 0 and not text[0].isspace()):
      _UpperCamelCase       			=''' ''' + text
    return (text, kwargs)













'''simple docstring'''






import contextlib
from multiprocessing import Pool, RLock

from tqdm.auto import tqdm

from ..utils import experimental, logging


__lowerCamelCase						: Union[str, Any]		=   logging.get_logger(__name__)







class 		UpperCAmelCase   :


  """simple docstring"""







  lowerCAmelCase_					=				None




@experimental
def 					_a   (__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  if ParallelBackendConfig.backend_name is None:
    return _map_with_multiprocessing_pool(
        __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   )

  return _map_with_joblib(__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   )


def 					_a   (__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  _UpperCamelCase       			=num_proc if num_proc <= len(__SCREAMING_SNAKE_CASE   ) else len(__SCREAMING_SNAKE_CASE   )
  _UpperCamelCase       			=[]  # We organize the splits ourselve (contiguous splits)
  for index in range(__SCREAMING_SNAKE_CASE   ):
    _UpperCamelCase       			=len(__SCREAMING_SNAKE_CASE   ) // num_proc
    _UpperCamelCase       			=len(__SCREAMING_SNAKE_CASE   ) % num_proc
    _UpperCamelCase       			=div * index + min(__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   )
    _UpperCamelCase       			=start + div + (1 if index < mod else 0)
    split_kwds.append((function, iterable[start:end], types, index, disable_tqdm, desc)   )

  if len(__SCREAMING_SNAKE_CASE   ) != sum(len(i[1]   ) for i in split_kwds   ):
    raise ValueError(
        f'''Error dividing inputs iterable among processes. '''
        f'''Total number of objects {len(__SCREAMING_SNAKE_CASE   )}, '''
        f'''length: {sum(len(i[1]   ) for i in split_kwds   )}'''   )

  logger.info(
      f'''Spawning {num_proc} processes for {len(__SCREAMING_SNAKE_CASE   )} objects in slices of {[len(i[1]   ) for i in split_kwds]}'''   )
  _UpperCamelCase			,     _UpperCamelCase       			=None, None
  if not disable_tqdm:
    _UpperCamelCase			,     _UpperCamelCase       			=(RLock(),), tqdm.set_lock
  with Pool(__SCREAMING_SNAKE_CASE  ,      initargs=__SCREAMING_SNAKE_CASE  ,      initializer=__SCREAMING_SNAKE_CASE   ) as pool:
    _UpperCamelCase       			=pool.map(__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   )
  logger.info(f'''Finished {num_proc} processes'''   )
  _UpperCamelCase       			=[obj for proc_res in mapped for obj in proc_res]
  logger.info(f'''Unpacked {len(__SCREAMING_SNAKE_CASE   )} objects'''   )

  return mapped


def 					_a   (__SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE  ,      __SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  import joblib

  with joblib.parallel_backend(ParallelBackendConfig.backend_name  ,      n_jobs=__SCREAMING_SNAKE_CASE   ):
    return joblib.Parallel()(
        joblib.delayed(__SCREAMING_SNAKE_CASE   )((function, obj, types, None, True, None)   ) for obj in iterable   )


@experimental
@contextlib.contextmanager
def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  _UpperCamelCase       			=backend_name

  if backend_name == "spark":
    from joblibspark import register_spark

    register_spark()

    # TODO: call create_cache_and_write_probe if "download" in steps
    # TODO: raise NotImplementedError when Dataset.map etc is called

  try:
    yield
  finally:
    _UpperCamelCase       			=None






