





'''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 importlib.util
import os
import platform
from argparse import ArgumentParser

import huggingface_hub

from .. import __version__ as version
from ..utils import (
    is_accelerate_available,
    is_flax_available,
    is_safetensors_available,
    is_tf_available,
    is_torch_available,
)
from . import BaseTransformersCLICommand


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  return EnvironmentCommand()


def 					_a   (__SCREAMING_SNAKE_CASE   ):


  """simple docstring"""

  return EnvironmentCommand(args.accelerate_config_file   )







class 		UpperCAmelCase   (				lowercase_):


  """simple docstring"""







  @staticmethod
  def   UpperCamelCase__      (				UpperCamelCase__    :					ArgumentParser  )     ->						Union[str, Any]:
    _UpperCamelCase       			=parser.add_parser('''env'''  )
    download_parser.set_defaults(func=UpperCamelCase__  )
    download_parser.add_argument(
        '''--accelerate-config_file'''							,	default=UpperCamelCase__							,	help='''The accelerate config file to use for the default values in the launching script.'''							,	)
    download_parser.set_defaults(func=UpperCamelCase__  )


  def __init__(				self    :					Tuple							,	UpperCamelCase__    :					Dict							,	*UpperCamelCase__    :					str  )     ->						None:
    _UpperCamelCase       			=accelerate_config_file


  def   UpperCamelCase__      (				self    :					str  )     ->						int:
    _UpperCamelCase       			='''not installed'''
    if is_safetensors_available():
      import safetensors

      _UpperCamelCase       			=safetensors.__version__
    elif importlib.util.find_spec('''safetensors'''  ) is not None:
      import safetensors

      _UpperCamelCase       			=F'''{safetensors.__version__} but is ignored because of PyTorch version too old.'''

    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			=_UpperCamelCase       			='''not found'''
    if is_accelerate_available():
      import accelerate
      from accelerate.commands.config import default_config_file, load_config_from_file

      _UpperCamelCase       			=accelerate.__version__
      # Get the default from the config file.
      if self._accelerate_config_file is not None or os.path.isfile(UpperCamelCase__  ):
        _UpperCamelCase       			=load_config_from_file(self._accelerate_config_file  ).to_dict()

      _UpperCamelCase       			=(
          '''\n'''.join([F'''\t- {prop}: {val}''' for prop, val in accelerate_config.items()]  )
          if isinstance(UpperCamelCase__							,	UpperCamelCase__  )
          else F'''\t{accelerate_config}'''
      )

    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			='''NA'''
    if is_torch_available():
      import torch

      _UpperCamelCase       			=torch.__version__
      _UpperCamelCase       			=torch.cuda.is_available()

    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			='''NA'''
    if is_tf_available():
      import tensorflow as tf

      _UpperCamelCase       			=tf.__version__
      try:
        # deprecated in v2.1
        _UpperCamelCase       			=tf.test.is_gpu_available()
      except AttributeError:
        # returns list of devices, convert to bool
        _UpperCamelCase       			=bool(tf.config.list_physical_devices('''GPU'''  )  )

    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			='''not installed'''
    _UpperCamelCase       			='''NA'''
    if is_flax_available():
      import flax
      import jax
      import jaxlib

      _UpperCamelCase       			=flax.__version__
      _UpperCamelCase       			=jax.__version__
      _UpperCamelCase       			=jaxlib.__version__
      _UpperCamelCase       			=jax.lib.xla_bridge.get_backend().platform

    _UpperCamelCase       			={
        '''`transformers` version''': version,
        '''Platform''': platform.platform(),
        '''Python version''': platform.python_version(),
        '''Huggingface_hub version''': huggingface_hub.__version__,
        '''Safetensors version''': F'''{safetensors_version}''',
        '''Accelerate version''': F'''{accelerate_version}''',
        '''Accelerate config''': F'''{accelerate_config_str}''',
        '''PyTorch version (GPU?)''': F'''{pt_version} ({pt_cuda_available})''',
        '''Tensorflow version (GPU?)''': F'''{tf_version} ({tf_cuda_available})''',
        '''Flax version (CPU?/GPU?/TPU?)''': F'''{flax_version} ({jax_backend})''',
        '''Jax version''': F'''{jax_version}''',
        '''JaxLib version''': F'''{jaxlib_version}''',
        '''Using GPU in script?''': '''<fill in>''',
        '''Using distributed or parallel set-up in script?''': '''<fill in>''',
    }

    print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n'''  )
    print(self.format_dict(UpperCamelCase__  )  )

    return info




  @staticmethod
  def   UpperCamelCase__      (				UpperCamelCase__    :					Optional[Any]  )     ->						Dict:
    return "\n".join([F'''- {prop}: {val}''' for prop, val in d.items()]  ) + "\n"






