


"""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__      				=   logging.get_logger(__name__)


lowerCAmelCase__      				=   {'''vocab_file''': '''vocab.json''', '''merges_file''': '''merges.txt'''}

# See all BART models at https://huggingface.co/models?filter=bart
lowerCAmelCase__      				=   {
    '''vocab_file''': {
        '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/vocab.json''',
        '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/vocab.json''',
        '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json''',
        '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json''',
        '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json''',
        '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json''',
    },
    '''merges_file''': {
        '''facebook/bart-base''': '''https://huggingface.co/facebook/bart-base/resolve/main/merges.txt''',
        '''facebook/bart-large''': '''https://huggingface.co/facebook/bart-large/resolve/main/merges.txt''',
        '''facebook/bart-large-mnli''': '''https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt''',
        '''facebook/bart-large-cnn''': '''https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt''',
        '''facebook/bart-large-xsum''': '''https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt''',
        '''yjernite/bart_eli5''': '''https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt''',
    },
}

lowerCAmelCase__      				=   {
    '''facebook/bart-base''': 1_024,
    '''facebook/bart-large''': 1_024,
    '''facebook/bart-large-mnli''': 1_024,
    '''facebook/bart-large-cnn''': 1_024,
    '''facebook/bart-large-xsum''': 1_024,
    '''yjernite/bart_eli5''': 1_024,
}
@lru_cache()
def 					a__			(				):


  '''simple docstring'''







  lowerCAmelCase     :     Optional[Any]								=							(
      list(range(ord("!"				)				,      ord("~"				) + 1				)				) + list(range(ord("¡"				)				,      ord("¬"				) + 1				)				) + list(range(ord("®"				)				,      ord("ÿ"				) + 1				)				)
  )
  lowerCAmelCase     :     int								=							bs[:]
  lowerCAmelCase     :     List[str]								=							0
  for b in range(2**8				):
    if b not in bs:
      bs.append(SCREAMING_SNAKE_CASE				)
      cs.append(2**8 + n				)
      n += 1
  lowerCAmelCase     :     Optional[int]								=							[chr(SCREAMING_SNAKE_CASE				) for n in cs]
  return dict(zip(SCREAMING_SNAKE_CASE				,      SCREAMING_SNAKE_CASE				)				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    Optional[int]				):


  '''simple docstring'''







  lowerCAmelCase     :     Any								=							set()
  lowerCAmelCase     :     Union[str, Any]								=							word[0]
  for char in word[1:]:
    pairs.add((prev_char, char)				)
    lowerCAmelCase     :     str								=							char
  return pairs





class       SCREAMING_SNAKE_CASE__				(		lowercase				):
       """simple docstring"""


       a  :				Any   =VOCAB_FILES_NAMES
       a  :				List[Any]   =PRETRAINED_VOCAB_FILES_MAP
       a  :				Optional[Any]   =PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       a  :				Dict   =["input_ids", "attention_mask"]

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






         """simple docstring"""





         lowerCAmelCase     :     List[str]								=							AddedToken(snake_case__		,     lstrip=snake_case__		,     rstrip=snake_case__						) if isinstance(snake_case__		,     snake_case__						) else bos_token
         lowerCAmelCase     :     Optional[int]								=							AddedToken(snake_case__		,     lstrip=snake_case__		,     rstrip=snake_case__						) if isinstance(snake_case__		,     snake_case__						) else eos_token
         lowerCAmelCase     :     Tuple								=							AddedToken(snake_case__		,     lstrip=snake_case__		,     rstrip=snake_case__						) if isinstance(snake_case__		,     snake_case__						) else sep_token
         lowerCAmelCase     :     List[Any]								=							AddedToken(snake_case__		,     lstrip=snake_case__		,     rstrip=snake_case__						) if isinstance(snake_case__		,     snake_case__						) else cls_token
         lowerCAmelCase     :     Any								=							AddedToken(snake_case__		,     lstrip=snake_case__		,     rstrip=snake_case__						) if isinstance(snake_case__		,     snake_case__						) else unk_token
         lowerCAmelCase     :     Any								=							AddedToken(snake_case__		,     lstrip=snake_case__		,     rstrip=snake_case__						) if isinstance(snake_case__		,     snake_case__						) else pad_token

         # Mask token behave like a normal word, i.e. include the space before it
         lowerCAmelCase     :     List[str]								=							AddedToken(snake_case__		,     lstrip=snake_case__		,     rstrip=snake_case__						) if isinstance(snake_case__		,     snake_case__						) else mask_token

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

         with open(snake_case__		,     encoding="utf-8"						) as vocab_handle:
           lowerCAmelCase     :     Union[str, Any]								=							json.load(snake_case__						)
         lowerCAmelCase     :     Union[str, Any]								=							{v: k for k, v in self.encoder.items()}
         lowerCAmelCase     :     Union[str, Any]								=							errors  # how to handle errors in decoding
         lowerCAmelCase     :     int								=							bytes_to_unicode()
         lowerCAmelCase     :     List[Any]								=							{v: k for k, v in self.byte_encoder.items()}
         with open(snake_case__		,     encoding="utf-8"						) as merges_handle:
           lowerCAmelCase     :     Dict								=							merges_handle.read().split("\n"						)[1:-1]
         lowerCAmelCase     :     Tuple								=							[tuple(merge.split()						) for merge in bpe_merges]
         lowerCAmelCase     :     Union[str, Any]								=							dict(zip(snake_case__		,     range(len(snake_case__						)						)						)						)
         lowerCAmelCase     :     str								=							{}
         lowerCAmelCase     :     Union[str, Any]								=							add_prefix_space

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

       @property
       def        lowercase__							(						self						):






         """simple docstring"""





         return len(self.encoder						)

       def        lowercase__							(						self						):






         """simple docstring"""





         return dict(self.encoder		,     **self.added_tokens_encoder						)

       def        lowercase__							(						self		,     snake_case__						):






         """simple docstring"""





         if token in self.cache:
           return self.cache[token]
         lowerCAmelCase     :     Tuple								=							tuple(snake_case__						)
         lowerCAmelCase     :     Tuple								=							get_pairs(snake_case__						)

         if not pairs:
           return token

         while True:
           lowerCAmelCase     :     Optional[Any]								=							min(snake_case__		,     key=lambda snake_case__						: self.bpe_ranks.get(snake_case__		,     float("inf"						)						)						)
           if bigram not in self.bpe_ranks:
             break
           lowerCAmelCase						,  lowerCAmelCase     :     Tuple								=							bigram
           lowerCAmelCase     :     Optional[int]								=							[]
           lowerCAmelCase     :     str								=							0
           while i < len(snake_case__						):
             try:
               lowerCAmelCase     :     Dict								=							word.index(snake_case__		,     snake_case__						)
             except ValueError:
               new_word.extend(word[i:]						)
               break
             else:
               new_word.extend(word[i:j]						)
               lowerCAmelCase     :     List[str]								=							j

             if word[i] == first and i < len(snake_case__						) - 1 and word[i + 1] == second:
               new_word.append(first + second						)
               i += 2
             else:
               new_word.append(word[i]						)
               i += 1
           lowerCAmelCase     :     Optional[Any]								=							tuple(snake_case__						)
           lowerCAmelCase     :     Any								=							new_word
           if len(snake_case__						) == 1:
             break
           else:
             lowerCAmelCase     :     List[str]								=							get_pairs(snake_case__						)
         lowerCAmelCase     :     List[str]								=							" ".join(snake_case__						)
         lowerCAmelCase     :     Tuple								=							word
         return word

       def        lowercase__							(						self		,     snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     List[str]								=							[]
         for token in re.findall(self.pat		,     snake_case__						):
           lowerCAmelCase     :     Optional[Any]								=							"".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(snake_case__						).split(" "						)						)
         return bpe_tokens

       def        lowercase__							(						self		,     snake_case__						):






         """simple docstring"""





         return self.encoder.get(snake_case__		,     self.encoder.get(self.unk_token						)						)

       def        lowercase__							(						self		,     snake_case__						):






         """simple docstring"""





         return self.decoder.get(snake_case__						)

       def        lowercase__							(						self		,     snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     List[str]								=							"".join(snake_case__						)
         lowerCAmelCase     :     Tuple								=							bytearray([self.byte_decoder[c] for c in text]						).decode("utf-8"		,     errors=self.errors						)
         return text

       def        lowercase__							(						self		,     snake_case__		,     snake_case__ = None						):






         """simple docstring"""





         if not os.path.isdir(snake_case__						):
           logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""						)
           return
         lowerCAmelCase     :     Optional[int]								=							os.path.join(
             snake_case__		,     (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]						)
         lowerCAmelCase     :     Tuple								=							os.path.join(
             snake_case__		,     (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]						)

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

         lowerCAmelCase     :     int								=							0
         with open(snake_case__		,     "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 snake_case__						: 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     :     int								=							token_index
             writer.write(" ".join(snake_case__						) + "\n"						)
             index += 1

         return vocab_file, merge_file

       def        lowercase__							(						self		,     snake_case__		,     snake_case__ = None						):






         """simple docstring"""





         if token_ids_a is None:
           return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
         lowerCAmelCase     :     Union[str, Any]								=							[self.cls_token_id]
         lowerCAmelCase     :     Optional[int]								=							[self.sep_token_id]
         return cls + token_ids_a + sep + sep + token_ids_a + sep

       def        lowercase__							(						self		,     snake_case__		,     snake_case__ = None		,     snake_case__ = False						):






         """simple docstring"""





         if already_has_special_tokens:
           return super().get_special_tokens_mask(
               token_ids_a=snake_case__		,     token_ids_a=snake_case__		,     already_has_special_tokens=snake_case__						)

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

       def        lowercase__							(						self		,     snake_case__		,     snake_case__ = None						):






         """simple docstring"""





         lowerCAmelCase     :     Union[str, Any]								=							[self.sep_token_id]
         lowerCAmelCase     :     Dict								=							[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        lowercase__							(						self		,     snake_case__		,     snake_case__=False		,     **snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     Union[str, Any]								=							kwargs.pop("add_prefix_space"		,     self.add_prefix_space						)
         if (is_split_into_words or add_prefix_space) and (len(snake_case__						) > 0 and not text[0].isspace()):
           lowerCAmelCase     :     List[Any]								=							" " + text
         return (text, kwargs)









"""simple docstring"""







import jax.numpy as jnp

from ...utils import logging
from ..ta.modeling_flax_ta import FlaxTaEncoderModel, FlaxTaForConditionalGeneration, FlaxTaModel
from .configuration_mta import MTaConfig


lowerCAmelCase__      				=   logging.get_logger(__name__)

lowerCAmelCase__      				=   '''T5Config'''
def 					a__			(				SCREAMING_SNAKE_CASE    :    jnp.array				,      SCREAMING_SNAKE_CASE    :    int				,      SCREAMING_SNAKE_CASE    :    int				):


  '''simple docstring'''







  lowerCAmelCase     :     List[str]								=							jnp.zeros_like(SCREAMING_SNAKE_CASE				)
  lowerCAmelCase     :     Optional[int]								=							shifted_input_ids.at[:, 1:].set(input_ids[:, :-1]				)
  lowerCAmelCase     :     List[str]								=							shifted_input_ids.at[:, 0].set(SCREAMING_SNAKE_CASE				)

  lowerCAmelCase     :     str								=							jnp.where(shifted_input_ids == -1_0_0				,      SCREAMING_SNAKE_CASE				,      SCREAMING_SNAKE_CASE				)
  return shifted_input_ids


class       SCREAMING_SNAKE_CASE__				(		lowercase				):
       """simple docstring"""


       a  :				List[Any]   ="mt5"
       a  :				Tuple   =MTaConfig


class       SCREAMING_SNAKE_CASE__				(		lowercase				):
       """simple docstring"""


       a  :				Union[str, Any]   ="mt5"
       a  :				Optional[Any]   =MTaConfig


class       SCREAMING_SNAKE_CASE__				(		lowercase				):
       """simple docstring"""


       a  :				str   ="mt5"
       a  :				Dict   =MTaConfig





