






from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__snake_case      :      List[Any]             =       logging.get_logger(__name__)







def 		_UpperCamelCase				(      UpperCamelCase_    :   Union[tf.Tensor, np.ndarray]						)					->				List[int]:

						"""simple docstring"""



						if isinstance(UpperCamelCase_      ,    np.ndarray						):
												return list(tensor.shape						)

						lowerCAmelCase__        =  tf.shape(UpperCamelCase_						)

						if tensor.shape == tf.TensorShape(UpperCamelCase_						):
												return dynamic

						lowerCAmelCase__        =  tensor.shape.as_list()

						return [dynamic[i] if s is None else s for i, s in enumerate(UpperCamelCase_						)]







def 		_UpperCamelCase				(      UpperCamelCase_    :   tf.Tensor      ,    UpperCamelCase_    :   Optional[int] = None      ,    UpperCamelCase_    :   Optional[str] = None						)					->				tf.Tensor:

						"""simple docstring"""



						return tf.nn.softmax(logits=logits + 1e-9      ,    axis=UpperCamelCase_      ,    name=UpperCamelCase_						)







def 		_UpperCamelCase				(      UpperCamelCase_    :   Tuple      ,    UpperCamelCase_    :   Optional[Any]      ,    UpperCamelCase_    :   List[Any]      ,    UpperCamelCase_    :   Tuple=1e-5      ,    UpperCamelCase_    :   Union[str, Any]=-1						)					->				Union[str, Any]:

						"""simple docstring"""



						if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(UpperCamelCase_      ,    UpperCamelCase_						):
												raise NotImplementedError('Only 1D weight and bias tensors are supported for now, with only a single axis.'						)

						# Get mean and variance on the axis to be normalized
						lowerCAmelCase__  ,    lowerCAmelCase__        =  tf.nn.moments(UpperCamelCase_      ,    axes=[axis]      ,    keepdims=UpperCamelCase_						)

						if axis != -1:
												# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
												# on every dimension except axis
												lowerCAmelCase__        =  [1] * inputs.shape.rank
												lowerCAmelCase__        =  shape_list(UpperCamelCase_						)[axis]
												lowerCAmelCase__        =  tf.reshape(UpperCamelCase_      ,    UpperCamelCase_						)
												lowerCAmelCase__        =  tf.reshape(UpperCamelCase_      ,    UpperCamelCase_						)

						# Compute layer normalization using the batch_normalization
						# function.
						lowerCAmelCase__        =  tf.nn.batch_normalization(
						    UpperCamelCase_      ,    UpperCamelCase_      ,    UpperCamelCase_      ,    offset=UpperCamelCase_      ,    scale=UpperCamelCase_      ,    variance_epsilon=UpperCamelCase_      ,    )
						return outputs







def 		_UpperCamelCase				(      UpperCamelCase_    :   Any      ,    UpperCamelCase_    :   Optional[int]=0      ,    UpperCamelCase_    :   List[str]=-1						)					->				List[str]:

						"""simple docstring"""



						if end_dim < 0:
												end_dim += input.shape.rank
						if start_dim < 0:
												start_dim += input.shape.rank

						if start_dim == end_dim:
												return input

						lowerCAmelCase__        =  tf.shape(UpperCamelCase_						)
						lowerCAmelCase__        =  tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]						)
						lowerCAmelCase__        =  tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]      ,    axis=0						)
						return tf.reshape(UpperCamelCase_      ,    UpperCamelCase_						)







def 		_UpperCamelCase				(      UpperCamelCase_    :   tf.Tensor						)					->				tf.Tensor:

						"""simple docstring"""



						if not isinstance(UpperCamelCase_      ,    tf.Tensor						):
												lowerCAmelCase__        =  tf.convert_to_tensor(UpperCamelCase_						)  # Catches stray NumPy inputs
						if encoder_attention_mask.shape.rank == 3:
												lowerCAmelCase__        =  encoder_attention_mask[:, None, :, :]
						if encoder_attention_mask.shape.rank == 2:
												lowerCAmelCase__        =  encoder_attention_mask[:, None, None, :]
						# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
						# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
						# /transformer/transformer_layers.py#L270
						# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
						# encoder_extended_attention_mask.transpose(-1, -2))
						lowerCAmelCase__        =  (
						    tf.cast(1      ,    encoder_attention_mask.dtype						) - encoder_extended_attention_mask
						) * encoder_extended_attention_mask.dtype.min

						return encoder_extended_attention_mask







def 		_UpperCamelCase				(      UpperCamelCase_    :   tf.Tensor      ,    UpperCamelCase_    :   int      ,    UpperCamelCase_    :   str = "input_ids"						)					->				None:

						"""simple docstring"""



						tf.debugging.assert_less(
						    UpperCamelCase_      ,    tf.cast(UpperCamelCase_      ,    dtype=tensor.dtype						)      ,    message=(
						        F"The maximum value of {tensor_name} ({tf.math.reduce_max(UpperCamelCase_						)}) must be smaller than the embedding "
						        F"layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."
						    )      ,    )







def 		_UpperCamelCase				(      UpperCamelCase_    :   List[Any]      ,    UpperCamelCase_    :   List[str]      ,    UpperCamelCase_    :   str						)					->				List[str]:

						"""simple docstring"""



						lowerCAmelCase__        =  6_4512
						# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
						# because in that case even chunking the array would not make the saving
						# possible.
						lowerCAmelCase__        =  [x for x in data if len(UpperCamelCase_						) > HDF5_OBJECT_HEADER_LIMIT]

						# Expecting this to never be true.
						if bad_attributes:
												raise RuntimeError(
												    'The following attributes cannot be saved to HDF5 file because '
												    F"they are larger than {HDF5_OBJECT_HEADER_LIMIT} "
												    F"bytes: {bad_attributes}"						)

						lowerCAmelCase__        =  np.asarray(UpperCamelCase_						)

						lowerCAmelCase__        =  1
						lowerCAmelCase__        =  np.array_split(UpperCamelCase_      ,    UpperCamelCase_						)

						# This will never loop forever thanks to the test above.
						while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data						):
												num_chunks += 1
												lowerCAmelCase__        =  np.array_split(UpperCamelCase_      ,    UpperCamelCase_						)

						if num_chunks > 1:
												for chunk_id, chunk_data in enumerate(UpperCamelCase_						):
																		lowerCAmelCase__        =  chunk_data
						else:
												lowerCAmelCase__        =  data







def 		_UpperCamelCase				(      UpperCamelCase_    :   List[Any]      ,    UpperCamelCase_    :   int						)					->				Any:

						"""simple docstring"""



						if name in group.attrs:
												lowerCAmelCase__        =  [n.decode('utf8'						) if hasattr(UpperCamelCase_      ,    'decode'						) else n for n in group.attrs[name]]
						else:
												lowerCAmelCase__        =  []
												lowerCAmelCase__        =  0
												while "%s%d" % (name, chunk_id) in group.attrs:
																		data.extend(
																		    [n.decode('utf8'						) if hasattr(UpperCamelCase_      ,    'decode'						) else n for n in group.attrs['%s%d' % (name, chunk_id)]]						)
																		chunk_id += 1
						return data







def 		_UpperCamelCase				(      UpperCamelCase_    :   Union[str, Any]						)					->				str:

						"""simple docstring"""



						def _expand_single_ad_tensor(UpperCamelCase_    :   Union[str, Any]						):
												if isinstance(UpperCamelCase_      ,    tf.Tensor						) and t.shape.rank == 1:
																		return tf.expand_dims(UpperCamelCase_      ,    axis=-1						)
												return t

						return tf.nest.map_structure(_expand_single_ad_tensor      ,    UpperCamelCase_						)













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

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding, EncodedInput
from ...utils import PaddingStrategy, logging


__snake_case      :      Any             =       logging.get_logger(__name__)


__snake_case      :      Union[str, Any]             =       {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt"""}

# See all LED models at https://huggingface.co/models?filter=LED
__snake_case      :      Optional[Any]             =       {
    """vocab_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json""",
    },
}

__snake_case      :      List[str]             =       {
    """allenai/led-base-16384""": 1_63_84,
}







@lru_cache()
# Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode
def 		_UpperCamelCase				(      )					->				int:

						"""simple docstring"""



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







def 		_UpperCamelCase				(      UpperCamelCase_    :   Optional[Any]						)					->				Dict:

						"""simple docstring"""



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


class       __SCREAMING_SNAKE_CASE   (				__lowercase):
						_SCREAMING_SNAKE_CASE		:    Optional[int]						=   VOCAB_FILES_NAMES
						_SCREAMING_SNAKE_CASE		:    Optional[int]						=   PRETRAINED_VOCAB_FILES_MAP
						_SCREAMING_SNAKE_CASE		:    Optional[Any]						=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						_SCREAMING_SNAKE_CASE		:    Any						=   ['''input_ids''', '''attention_mask''']






						def __init__(		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase="replace"       ,  _UpperCamelCase="<s>"       ,  _UpperCamelCase="</s>"       ,  _UpperCamelCase="</s>"       ,  _UpperCamelCase="<s>"       ,  _UpperCamelCase="<unk>"       ,  _UpperCamelCase="<pad>"       ,  _UpperCamelCase="<mask>"       ,  _UpperCamelCase=False       ,  **_UpperCamelCase       ,  ):






												"""simple docstring"""
												lowerCAmelCase__        =  AddedToken(_UpperCamelCase       ,  lstrip=_UpperCamelCase       ,  rstrip=_UpperCamelCase				) if isinstance(_UpperCamelCase       ,  _UpperCamelCase				) else bos_token
												lowerCAmelCase__        =  AddedToken(_UpperCamelCase       ,  lstrip=_UpperCamelCase       ,  rstrip=_UpperCamelCase				) if isinstance(_UpperCamelCase       ,  _UpperCamelCase				) else eos_token
												lowerCAmelCase__        =  AddedToken(_UpperCamelCase       ,  lstrip=_UpperCamelCase       ,  rstrip=_UpperCamelCase				) if isinstance(_UpperCamelCase       ,  _UpperCamelCase				) else sep_token
												lowerCAmelCase__        =  AddedToken(_UpperCamelCase       ,  lstrip=_UpperCamelCase       ,  rstrip=_UpperCamelCase				) if isinstance(_UpperCamelCase       ,  _UpperCamelCase				) else cls_token
												lowerCAmelCase__        =  AddedToken(_UpperCamelCase       ,  lstrip=_UpperCamelCase       ,  rstrip=_UpperCamelCase				) if isinstance(_UpperCamelCase       ,  _UpperCamelCase				) else unk_token
												lowerCAmelCase__        =  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
												lowerCAmelCase__        =  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:
																		lowerCAmelCase__        =  json.load(_UpperCamelCase				)
												lowerCAmelCase__        =  {v: k for k, v in self.encoder.items()}
												lowerCAmelCase__        =  errors  # how to handle errors in decoding
												lowerCAmelCase__        =  bytes_to_unicode()
												lowerCAmelCase__        =  {v: k for k, v in self.byte_encoder.items()}
												with open(_UpperCamelCase       ,  encoding='utf-8'				) as merges_handle:
																		lowerCAmelCase__        =  merges_handle.read().split('\n'				)[1:-1]
												lowerCAmelCase__        =  [tuple(merge.split()				) for merge in bpe_merges]
												lowerCAmelCase__        =  dict(zip(_UpperCamelCase       ,  range(len(_UpperCamelCase				)				)				)				)
												lowerCAmelCase__        =  {}
												lowerCAmelCase__        =  add_prefix_space

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






						@property
						# Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size
						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												return len(self.encoder				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												return dict(self.encoder       ,  **self.added_tokens_encoder				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												if token in self.cache:
																		return self.cache[token]
												lowerCAmelCase__        =  tuple(_UpperCamelCase				)
												lowerCAmelCase__        =  get_pairs(_UpperCamelCase				)

												if not pairs:
																		return token

												while True:
																		lowerCAmelCase__        =  min(_UpperCamelCase       ,  key=lambda _UpperCamelCase				: self.bpe_ranks.get(_UpperCamelCase       ,  float('inf'				)				)				)
																		if bigram not in self.bpe_ranks:
																								break
																		lowerCAmelCase__  ,    lowerCAmelCase__        =  bigram
																		lowerCAmelCase__        =  []
																		lowerCAmelCase__        =  0
																		while i < len(_UpperCamelCase				):
																								try:
																														lowerCAmelCase__        =  word.index(_UpperCamelCase       ,  _UpperCamelCase				)
																								except ValueError:
																														new_word.extend(word[i:]				)
																														break
																								else:
																														new_word.extend(word[i:j]				)
																														lowerCAmelCase__        =  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
																		lowerCAmelCase__        =  tuple(_UpperCamelCase				)
																		lowerCAmelCase__        =  new_word
																		if len(_UpperCamelCase				) == 1:
																								break
																		else:
																								lowerCAmelCase__        =  get_pairs(_UpperCamelCase				)
												lowerCAmelCase__        =  ' '.join(_UpperCamelCase				)
												lowerCAmelCase__        =  word
												return word






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  []
												for token in re.findall(self.pat       ,  _UpperCamelCase				):
																		lowerCAmelCase__        =  ''.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       ,  _UpperCamelCase				):






												"""simple docstring"""
												return self.encoder.get(_UpperCamelCase       ,  self.encoder.get(self.unk_token				)				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												return self.decoder.get(_UpperCamelCase				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  ''.join(_UpperCamelCase				)
												lowerCAmelCase__        =  bytearray([self.byte_decoder[c] for c in text]				).decode('utf-8'       ,  errors=self.errors				)
												return text






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase = None				):






												"""simple docstring"""
												if not os.path.isdir(_UpperCamelCase				):
																		logger.error(F"Vocabulary path ({save_directory}) should be a directory"				)
																		return
												lowerCAmelCase__        =  os.path.join(
												    _UpperCamelCase       ,  (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']				)
												lowerCAmelCase__        =  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'				)

												lowerCAmelCase__        =  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!'				)
																														lowerCAmelCase__        =  token_index
																								writer.write(' '.join(_UpperCamelCase				) + '\n'				)
																								index += 1

												return vocab_file, merge_file






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase = None				):






												"""simple docstring"""
												if token_ids_a is None:
																		return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
												lowerCAmelCase__        =  [self.cls_token_id]
												lowerCAmelCase__        =  [self.sep_token_id]
												return cls + token_ids_a + sep + sep + token_ids_a + sep






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase = None       ,  _UpperCamelCase = False				):






												"""simple docstring"""
												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       ,  _UpperCamelCase       ,  _UpperCamelCase = None				):






												"""simple docstring"""
												lowerCAmelCase__        =  [self.sep_token_id]
												lowerCAmelCase__        =  [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       ,  _UpperCamelCase       ,  _UpperCamelCase=False       ,  **_UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  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()):
																		lowerCAmelCase__        =  ' ' + text
												return (text, kwargs)







						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase = None       ,  _UpperCamelCase = PaddingStrategy.DO_NOT_PAD       ,  _UpperCamelCase = None       ,  _UpperCamelCase = None       ,  ):






												"""simple docstring"""
												lowerCAmelCase__        =  super()._pad(
												    encoded_inputs=_UpperCamelCase       ,  max_length=_UpperCamelCase       ,  padding_strategy=_UpperCamelCase       ,  pad_to_multiple_of=_UpperCamelCase       ,  return_attention_mask=_UpperCamelCase       ,  )

												# Load from model defaults
												if return_attention_mask is None:
																		lowerCAmelCase__        =  'attention_mask' in self.model_input_names

												if return_attention_mask and "global_attention_mask" in encoded_inputs:
																		lowerCAmelCase__        =  encoded_inputs[self.model_input_names[0]]
																		# `global_attention_mask` need to have the same length as other (sequential) inputs.
																		lowerCAmelCase__        =  len(encoded_inputs['global_attention_mask']				) != len(_UpperCamelCase				)

																		if needs_to_be_padded:
																								lowerCAmelCase__        =  len(_UpperCamelCase				) - len(encoded_inputs['global_attention_mask']				)

																								if self.padding_side == "right":
																														# Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
																														lowerCAmelCase__        =  (
																														    encoded_inputs['global_attention_mask'] + [-1] * difference
																														)
																								elif self.padding_side == "left":
																														lowerCAmelCase__        =  [-1] * difference + encoded_inputs[
																														    'global_attention_mask'
																														]
																								else:
																														raise ValueError('Invalid padding strategy:' + str(self.padding_side				)				)

												return encoded_inputs





