

import os
import re
import unicodedata
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union

import sentencepiece as spm

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


if is_torch_available():
      import torch


if TYPE_CHECKING:
      from transformers.pipelines.conversational import Conversation


_lowerCamelCase						    =  logging.get_logger(__name__)
_lowerCamelCase						    =  {'''vocab_file''': '''spiece.model'''}

_lowerCamelCase						    =  {
    '''vocab_file''': {
        '''AI-Sweden/gpt-sw3-126m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-350m''': '''https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-1.6b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-6.7b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model''',
        '''AI-Sweden/gpt-sw3-20b''': '''https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model''',
    }
}

_lowerCamelCase						    =  {
    '''AI-Sweden/gpt-sw3-126m''': 2048,
    '''AI-Sweden/gpt-sw3-350m''': 2048,
    '''AI-Sweden/gpt-sw3-1.6b''': 2048,
    '''AI-Sweden/gpt-sw3-6.7b''': 2048,
    '''AI-Sweden/gpt-sw3-20b''': 2048,
}

class       _SCREAMING_SNAKE_CASE	(snake_case__ ):
     lowerCAmelCase					=			VOCAB_FILES_NAMES
     lowerCAmelCase					=			PRETRAINED_VOCAB_FILES_MAP
     lowerCAmelCase					=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowerCAmelCase					=			['''input_ids''', '''attention_mask''']





     def __init__(       self :							int     ,  UpperCamelCase :							List[str]     ,  UpperCamelCase :							Union[str, Any]=False     ,  UpperCamelCase :							int=False     ,  UpperCamelCase :							Optional[Any]=False     ,  UpperCamelCase :							List[str]=None     ,  UpperCamelCase :							Any=None     ,  UpperCamelCase :							Optional[int]=None     ,  UpperCamelCase :							Optional[Any]=None     ,  UpperCamelCase :							Union[str, Any] = None     ,  **UpperCamelCase :							List[Any]     ,  )->Optional[int]:
      __SCREAMING_SNAKE_CASE       :    Any       =	{} if sp_model_kwargs is None else sp_model_kwargs

      __SCREAMING_SNAKE_CASE       :    str       =	kwargs.get("name_or_path"				)
      if name_or_path is None:
       logger.warning(
           "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b,"
           " you are testing the model, this can safely be ignored"				)
       __SCREAMING_SNAKE_CASE       :    Any       =	'None'

      # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing
      __SCREAMING_SNAKE_CASE       :    int       =	'<|endoftext|>' if eos_token is None else eos_token
      __SCREAMING_SNAKE_CASE       :    Any       =	'<unk>' if unk_token is None else unk_token
      if "gpt-sw3-7b" in name_or_path:
       __SCREAMING_SNAKE_CASE       :    Optional[int]       =	unk_token if pad_token is None else pad_token
       __SCREAMING_SNAKE_CASE       :    List[Any]       =	eos_token if bos_token is None else bos_token
      else:
       __SCREAMING_SNAKE_CASE       :    List[str]       =	'<pad>' if pad_token is None else pad_token
       __SCREAMING_SNAKE_CASE       :    Optional[int]       =	'<s>' if bos_token is None else bos_token

      super().__init__(
          do_lower_case=_A     ,  remove_space=_A     ,  keep_accents=_A     ,  bos_token=_A     ,  eos_token=_A     ,  unk_token=_A     ,  pad_token=_A     ,  sp_model_kwargs=self.sp_model_kwargs     ,  **_A     ,  )

      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	do_lower_case
      __SCREAMING_SNAKE_CASE       :    int       =	remove_space
      __SCREAMING_SNAKE_CASE       :    Any       =	keep_accents
      __SCREAMING_SNAKE_CASE       :    str       =	vocab_file

      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	spm.SentencePieceProcessor(**self.sp_model_kwargs				)
      self.sp_model.Load(_A				)

      # Used for whitespace normalization in input texts
      # fmt : off
      __SCREAMING_SNAKE_CASE       :    str       =	{' ', ' ', ' ', ' ', ' ', '　', ' ', ' ', ' ', ' ', '￼', ''}
      # fmt : on

      # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	re.compile(
          F"""[{"".join(map(_A     ,  list(range(0     ,  9				)				) + list(range(1_1     ,  3_2				)				) + list(range(1_2_7     ,  1_6_0				)				) + [1_6_0, 1_7_3, 8_2_0_3]				)				)}]"""				)





     def __getstate__(       self :							List[Any]				)->int:
      __SCREAMING_SNAKE_CASE       :    List[str]       =	self.__dict__.copy()
      __SCREAMING_SNAKE_CASE       :    Tuple       =	None
      return state





     def __setstate__(       self :							int     ,  UpperCamelCase :							Union[str, Any]				)->Union[str, Any]:
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	d

      # for backward compatibility
      if not hasattr(self     ,  "sp_model_kwargs"				):
       __SCREAMING_SNAKE_CASE       :    List[Any]       =	{}

      __SCREAMING_SNAKE_CASE       :    List[Any]       =	spm.SentencePieceProcessor(**self.sp_model_kwargs				)
      self.sp_model.Load(self.vocab_file				)





     @property
     # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size
     def 	__snake_case    (       self :							List[Any]				)->Optional[int]:
      return len(self.sp_model				)





     def 	__snake_case    (       self :							Union[str, Any]     ,  UpperCamelCase :							int				)->str:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	self.non_printing_characters_re.sub(""     ,  _A				)

      # Normalize whitespaces
      __SCREAMING_SNAKE_CASE       :    str       =	''.join([char if char not in self.whitespaces else " " for char in text]				)

      # NFC Unicode normalization
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	unicodedata.normalize("NFC"     ,  _A				)
      return text





     def 	__snake_case    (       self :							Optional[int]     ,  UpperCamelCase :							Optional[Any]     ,  **UpperCamelCase :							int				)->Dict:
      __SCREAMING_SNAKE_CASE       :    List[str]       =	self.preprocess_text(_A				)
      return self.sp_model.encode(_A     ,  out_type=_A				)





     def 	__snake_case    (       self :							Any     ,  UpperCamelCase :							Union[str, Any]				)->Dict:
      return self.sp_model.PieceToId(_A				)





     def 	__snake_case    (       self :							Any     ,  UpperCamelCase :							str				)->Any:
      return self.sp_model.IdToPiece(_A				)





     @staticmethod
     def 	__snake_case    (       UpperCamelCase :							Optional[Any]				)->str:
      return out_string





     def 	__snake_case    (       self :							Optional[Any]     ,  UpperCamelCase :							int				)->Tuple:
      __SCREAMING_SNAKE_CASE       :    int       =	[]
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	''
      __SCREAMING_SNAKE_CASE       :    List[str]       =	False
      for token in tokens:
       # make sure that special tokens are not decoded using sentencepiece model
       if token in self.all_special_tokens:
        # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document
        if not prev_is_special:
         out_string += " "

        out_string += self.sp_model.decode(_A				) + token
        __SCREAMING_SNAKE_CASE       :    Tuple       =	True
        __SCREAMING_SNAKE_CASE       :    int       =	[]
       else:
        current_sub_tokens.append(_A				)
        __SCREAMING_SNAKE_CASE       :    List[str]       =	False
      out_string += self.sp_model.decode(_A				)

      return out_string





     def 	__snake_case    (       self :							Dict				)->List[Any]:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	{self.convert_ids_to_tokens(_A				): i for i in range(self.vocab_size				)}
      vocab.update(self.added_tokens_encoder				)
      return vocab





     def 	__snake_case    (       self :							Tuple     ,  UpperCamelCase :							Any     ,  UpperCamelCase :							str = None				)->Union[str, Any]:
      if not os.path.isdir(_A				):
       logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""				)
       return
      __SCREAMING_SNAKE_CASE       :    List[str]       =	os.path.join(
          _A     ,  (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]				)

      if os.path.abspath(self.vocab_file				) != os.path.abspath(_A				) and os.path.isfile(self.vocab_file				):
       copyfile(self.vocab_file     ,  _A				)
      elif not os.path.isfile(self.vocab_file				):
       with open(_A     ,  "wb"				) as fi:
        __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	self.sp_model.serialized_model_proto()
        fi.write(_A				)

      return (out_vocab_file,)





     def 	__snake_case    (       self :							Optional[int]     ,  UpperCamelCase :							Dict     ,  UpperCamelCase :							Optional[Any] = False				)->str:

      if isinstance(_A     ,  _A				):
       __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	self.preprocess_text(_A				)
       __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	self.sp_model.encode(_A				)
      else:
       __SCREAMING_SNAKE_CASE       :    Any       =	[self.preprocess_text(_A				) for t in text]
       __SCREAMING_SNAKE_CASE       :    str       =	self.sp_model.encode(_A				)

      if return_tensors is True or return_tensors == "pt":
       __SCREAMING_SNAKE_CASE       :    Dict       =	torch.tensor(_A				)

      return token_ids





     def 	__snake_case    (       self :							str     ,  UpperCamelCase :							Optional[Any]				)->Optional[Any]:
      return self.sp_model.decode(_A				)






     def 	__snake_case    (       self :							int     ,  UpperCamelCase :							List[Any]				)->List[str]:
      __SCREAMING_SNAKE_CASE       :    Tuple       =	[F"""User: {text}""" if is_user else F"""Bot: {text}""" for is_user, text in conversation.iter_texts()]
      __SCREAMING_SNAKE_CASE       :    Any       =	(
          F"""{self.eos_token}{self.bos_token}""" + F"""{self.bos_token}""".join(_A				) + F"""{self.bos_token}Bot:"""
      )
      return self.encode(text=_A				)











import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from transformers import MaMaaaTokenizer, is_torch_available
from transformers.testing_utils import (
    get_tests_dir,
    nested_simplify,
    require_sentencepiece,
    require_tokenizers,
    require_torch,
    slow,
)
from transformers.utils import is_sentencepiece_available


if is_sentencepiece_available():
      from transformers.models.mam_aaa.tokenization_mam_aaa import VOCAB_FILES_NAMES, save_json

from ...test_tokenization_common import TokenizerTesterMixin


if is_sentencepiece_available():
      _lowerCamelCase						    =  get_tests_dir("""fixtures/test_sentencepiece.model""")


if is_torch_available():
      from transformers.models.mam_aaa.modeling_mam_aaa import shift_tokens_right

_lowerCamelCase						    =  128022
_lowerCamelCase						    =  128028

@require_sentencepiece
class       _SCREAMING_SNAKE_CASE	(UpperCamelCase			,    unittest.TestCase ):
     lowerCAmelCase					=			MaMaaaTokenizer
     lowerCAmelCase					=			False
     lowerCAmelCase					=			False
     lowerCAmelCase					=			True





     def 	__snake_case    (       self :							Union[str, Any]				)->Optional[Any]:
      super().setUp()

      __SCREAMING_SNAKE_CASE       :    int       =	["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"]
      __SCREAMING_SNAKE_CASE       :    List[str]       =	dict(zip(UpperCamelCase     ,  range(len(UpperCamelCase				)				)				)				)
      __SCREAMING_SNAKE_CASE       :    int       =	Path(self.tmpdirname				)
      save_json(UpperCamelCase     ,  save_dir / VOCAB_FILES_NAMES["vocab_file"]				)
      if not (save_dir / VOCAB_FILES_NAMES["spm_file"]).exists():
       copyfile(UpperCamelCase     ,  save_dir / VOCAB_FILES_NAMES["spm_file"]				)

      __SCREAMING_SNAKE_CASE       :    Any       =	MaMaaaTokenizer.from_pretrained(self.tmpdirname				)
      tokenizer.save_pretrained(self.tmpdirname				)





     def 	__snake_case    (       self :							Optional[int]     ,  **UpperCamelCase :							Any				)->Dict:
      return MaMaaaTokenizer.from_pretrained(self.tmpdirname     ,  **UpperCamelCase				)





     def 	__snake_case    (       self :							Dict     ,  UpperCamelCase :							List[str]				)->int:
      return (
          "This is a test",
          "This is a test",
      )





     def 	__snake_case    (       self :							str				)->Tuple:
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	"</s>"
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	0

      self.assertEqual(self.get_tokenizer()._convert_token_to_id(UpperCamelCase				)     ,  UpperCamelCase				)
      self.assertEqual(self.get_tokenizer()._convert_id_to_token(UpperCamelCase				)     ,  UpperCamelCase				)





     def 	__snake_case    (       self :							Tuple				)->Optional[Any]:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	self.get_tokenizer()
      __SCREAMING_SNAKE_CASE       :    Any       =	list(tokenizer.get_vocab().keys()				)

      self.assertEqual(vocab_keys[0]     ,  "</s>"				)
      self.assertEqual(vocab_keys[1]     ,  "<unk>"				)
      self.assertEqual(vocab_keys[-1]     ,  "<s>"				)
      self.assertEqual(len(UpperCamelCase				)     ,  tokenizer.vocab_size + len(tokenizer.get_added_vocab()				)				)





     @unittest.skip("Skip this test while all models are still to be uploaded."				)
     def 	__snake_case    (       self :							Dict				)->Dict:
      pass





     def 	__snake_case    (       self :							Union[str, Any]				)->Union[str, Any]:
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	self.get_tokenizer()

      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	tokenizer.tokenize("This is a test"				)
      self.assertListEqual(UpperCamelCase     ,  ["▁This", "▁is", "▁a", "▁t", "est"]				)

      self.assertListEqual(
          tokenizer.convert_tokens_to_ids(UpperCamelCase				)     ,  [2, 3, 4, 5, 6]     ,  )

      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	tokenizer.convert_ids_to_tokens([2, 3, 4, 5, 6]				)
      self.assertListEqual(UpperCamelCase     ,  ["▁This", "▁is", "▁a", "▁t", "est"]				)

      __SCREAMING_SNAKE_CASE       :    Any       =	tokenizer.convert_tokens_to_string(UpperCamelCase				)
      self.assertEqual(UpperCamelCase     ,  "This is a test"				)






     @slow
     def 	__snake_case    (       self :							Any				)->Union[str, Any]:
      # fmt: off
      __SCREAMING_SNAKE_CASE       :    Tuple       =	{"input_ids": [[1_2_8_0_2_2, 1_1_0_1_0_8, 3_9_7, 1_1, 3_8_2_7_2, 2_2_4_7, 1_2_4_8_1_1, 2_8_5, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 3_9_5_3_4, 4_4_2_8, 3_9_7, 1_0_1_9, 1_8_1_0_5, 1_5_8_6, 2_0_7, 7, 4_1_3_3_7, 1_6_7_8_6, 2_4_1, 7, 2_0_2_1_4, 1_7, 1_2_5_6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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
      # fmt: on

      self.tokenizer_integration_test_util(
          expected_encoding=UpperCamelCase     ,  model_name="facebook/m2m100_418M"     ,  revision="c168bae485c864188cf9aa0e4108b0b6934dc91e"     ,  )






@require_torch
@require_sentencepiece
@require_tokenizers
class       _SCREAMING_SNAKE_CASE	(unittest.TestCase ):
     lowerCAmelCase					=			"""facebook/m2m100_418M"""
     lowerCAmelCase					=			[
         """In my opinion, there are two levels of response from the French government.""",
         """NSA Affair Emphasizes Complete Lack of Debate on Intelligence""",
     ]
     lowerCAmelCase					=			[
         """Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.""",
         """L'affaire NSA souligne l'absence totale de débat sur le renseignement""",
     ]

     # fmt: off
     lowerCAmelCase					=			[EN_CODE, 593, 1949, 11_5781, 4, 7_1586, 4234, 6_0633, 12_6233, 432, 12_3808, 1_5592, 1197, 11_7132, 12_0618, 5, 2]





     @classmethod
     def 	__snake_case    (       cls :							List[Any]				)->Union[str, Any]:
      __SCREAMING_SNAKE_CASE       :    MaMaaaTokenizer       =	MaMaaaTokenizer.from_pretrained(
          cls.checkpoint_name     ,  src_lang="en"     ,  tgt_lang="fr"				)
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	1
      return cls





     def 	__snake_case    (       self :							Dict				)->Any:
      self.assertEqual(self.tokenizer.get_lang_id("ar"				)     ,  1_2_8_0_0_6				)
      self.assertEqual(self.tokenizer.get_lang_id("en"				)     ,  1_2_8_0_2_2				)
      self.assertEqual(self.tokenizer.get_lang_id("ro"				)     ,  1_2_8_0_7_6				)
      self.assertEqual(self.tokenizer.get_lang_id("mr"				)     ,  1_2_8_0_6_3				)





     def 	__snake_case    (       self :							Any				)->Union[str, Any]:
      __SCREAMING_SNAKE_CASE       :    str       =	self.tokenizer.get_vocab()
      self.assertEqual(len(UpperCamelCase				)     ,  self.tokenizer.vocab_size				)
      self.assertEqual(vocab["<unk>"]     ,  3				)
      self.assertIn(self.tokenizer.get_lang_token("en"				)     ,  UpperCamelCase				)





     def 	__snake_case    (       self :							List[Any]				)->str:
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	"en"
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	self.tokenizer.batch_encode_plus(self.src_text				).input_ids[0]
      self.assertListEqual(self.expected_src_tokens     ,  UpperCamelCase				)





     def 	__snake_case    (       self :							Union[str, Any]				)->List[Any]:
      self.assertIn(UpperCamelCase     ,  self.tokenizer.all_special_ids				)
      # fmt: off
      __SCREAMING_SNAKE_CASE       :    Dict       =	[FR_CODE, 5_3_6_4, 8_2, 8_6_4_2, 4, 2_9_4, 4_7, 8, 1_4_0_2_8, 1_3_6, 3_2_8_6, 9_7_0_6, 6, 9_0_7_9_7, 6, 1_4_4_0_1_2, 1_6_2, 8_8_1_2_8, 3_0_0_6_1, 5, 2]
      # fmt: on
      __SCREAMING_SNAKE_CASE       :    int       =	self.tokenizer.decode(UpperCamelCase     ,  skip_special_tokens=UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	self.tokenizer.decode(generated_ids[1:]     ,  skip_special_tokens=UpperCamelCase				)
      self.assertEqual(UpperCamelCase     ,  UpperCamelCase				)
      self.assertNotIn(self.tokenizer.eos_token     ,  UpperCamelCase				)





     def 	__snake_case    (       self :							Any				)->List[Any]:
      __SCREAMING_SNAKE_CASE       :    int       =	tempfile.mkdtemp()
      __SCREAMING_SNAKE_CASE       :    List[Any]       =	self.tokenizer.lang_token_to_id
      self.tokenizer.save_pretrained(UpperCamelCase				)
      __SCREAMING_SNAKE_CASE       :    Any       =	MaMaaaTokenizer.from_pretrained(UpperCamelCase				)
      self.assertDictEqual(new_tok.lang_token_to_id     ,  UpperCamelCase				)





     @require_torch
     def 	__snake_case    (       self :							Any				)->int:
      __SCREAMING_SNAKE_CASE       :    List[str]       =	"en"
      __SCREAMING_SNAKE_CASE       :    Dict       =	"fr"

      __SCREAMING_SNAKE_CASE       :    str       =	self.tokenizer(self.src_text     ,  text_target=self.tgt_text     ,  padding=UpperCamelCase     ,  return_tensors="pt"				)

      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	shift_tokens_right(
          batch["labels"]     ,  self.tokenizer.pad_token_id     ,  self.tokenizer.eos_token_id				)

      for k in batch:
       __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	batch[k].tolist()
      # batch = {k: v.tolist() for k,v in batch.items()}
      # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
      # batch.decoder_inputs_ids[0][0] ==
      assert batch.input_ids[1][0] == EN_CODE
      assert batch.input_ids[1][-1] == 2
      assert batch.labels[1][0] == FR_CODE
      assert batch.labels[1][-1] == 2
      assert batch.decoder_input_ids[1][:2] == [2, FR_CODE]





     @require_torch
     def 	__snake_case    (       self :							str				)->int:
      __SCREAMING_SNAKE_CASE       :    Optional[Any]       =	"mr"
      self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id("mr"				)]				)
      self.assertListEqual(self.tokenizer.suffix_tokens     ,  [self.tokenizer.eos_token_id]				)

      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	"zh"
      self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id("zh"				)]				)
      self.assertListEqual(self.tokenizer.suffix_tokens     ,  [self.tokenizer.eos_token_id]				)





     @require_torch
     def 	__snake_case    (       self :							Optional[Any]				)->List[Any]:
      __SCREAMING_SNAKE_CASE       :    Union[str, Any]       =	"mr"
      self.tokenizer._switch_to_target_mode()
      self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id("mr"				)]				)
      self.assertListEqual(self.tokenizer.suffix_tokens     ,  [self.tokenizer.eos_token_id]				)
      self.tokenizer._switch_to_input_mode()
      self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id(self.tokenizer.src_lang				)]				)

      __SCREAMING_SNAKE_CASE       :    Optional[int]       =	"zh"
      self.tokenizer._switch_to_target_mode()
      self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id("zh"				)]				)
      self.assertListEqual(self.tokenizer.suffix_tokens     ,  [self.tokenizer.eos_token_id]				)
      self.tokenizer._switch_to_input_mode()
      self.assertListEqual(self.tokenizer.prefix_tokens     ,  [self.tokenizer.get_lang_id(self.tokenizer.src_lang				)]				)






     @require_torch
     def 	__snake_case    (       self :							Tuple				)->Optional[int]:
      __SCREAMING_SNAKE_CASE       :    Any       =	self.tokenizer._build_translation_inputs("A test"     ,  return_tensors="pt"     ,  src_lang="en"     ,  tgt_lang="ar"				)

      self.assertEqual(
          nested_simplify(UpperCamelCase				)     ,  {
              # en_XX, A, test, EOS
              "input_ids": [[1_2_8_0_2_2, 5_8, 4_1_8_3, 2]],
              "attention_mask": [[1, 1, 1, 1]],
              # ar_AR
              "forced_bos_token_id": 1_2_8_0_0_6,
          }     ,  )






