

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():
  __UpperCAmelCase    				=     get_tests_dir('fixtures/test_sentencepiece.model')


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

__UpperCAmelCase    				=     1_2_8_0_2_2
__UpperCAmelCase    				=     1_2_8_0_2_8





@require_sentencepiece
class A__    ( A  ,		unittest.TestCase ):



 """simple docstring"""







 _lowercase     :					int      =						MaMaaaTokenizer
 _lowercase     :					Optional[Any]      =						False
 _lowercase     :					List[Any]      =						False
 _lowercase     :					Any      =						True

 def    __magic_name__       (		self :	Dict       ):






      '''simple docstring'''




      super().setUp()

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

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

 def    __magic_name__       (		self :	Any     ,						**A_ :	Tuple       ):






      '''simple docstring'''




      return MaMaaaTokenizer.from_pretrained(self.tmpdirname     ,						**A_       )

 def    __magic_name__       (		self :	Tuple     ,						A_ :	List[Any]       ):






      '''simple docstring'''




      return (
          "This is a test",
          "This is a test",
      )

 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Dict        =    "</s>"
      _lowerCAmelCase   :					List[Any]        =    0

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

 def    __magic_name__       (		self :	Union[str, Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Any        =    self.get_tokenizer()
      _lowerCAmelCase   :					Tuple        =    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(A_       )     ,						tokenizer.vocab_size + len(tokenizer.get_added_vocab()       )       )

 @unittest.skip("Skip this test while all models are still to be uploaded."       )
 def    __magic_name__       (		self :	List[str]       ):






      '''simple docstring'''




      pass

 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[Any]        =    self.get_tokenizer()

      _lowerCAmelCase   :					str        =    tokenizer.tokenize("This is a test"       )
      self.assertListEqual(A_     ,						["▁This", "▁is", "▁a", "▁t", "est"]       )

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

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

      _lowerCAmelCase   :					List[Any]        =    tokenizer.convert_tokens_to_string(A_       )
      self.assertEqual(A_     ,						"This is a test"       )


 @slow
 def    __magic_name__       (		self :	str       ):






      '''simple docstring'''




      _lowerCAmelCase   :					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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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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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=A_     ,						model_name="facebook/m2m100_418M"     ,						revision="c168bae485c864188cf9aa0e4108b0b6934dc91e"     ,						)





@require_torch
@require_sentencepiece
@require_tokenizers
class A__    ( unittest.TestCase ):



 """simple docstring"""







 _lowercase     :					Any      =						'''facebook/m2m100_418M'''
 _lowercase     :					str      =						[
     '''In my opinion, there are two levels of response from the French government.''',
     '''NSA Affair Emphasizes Complete Lack of Debate on Intelligence''',
 ]
 _lowercase     :					List[Any]      =						[
     '''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
 _lowercase     :					Union[str, Any]      =						[EN_CODE, 593, 1_949, 115_781, 4, 71_586, 4_234, 60_633, 126_233, 432, 123_808, 15_592, 1_197, 117_132, 120_618, 5, 2]

 @classmethod
 def    __magic_name__       (		cls :	Dict       ):






      '''simple docstring'''




      _lowerCAmelCase   :					MaMaaaTokenizer        =    MaMaaaTokenizer.from_pretrained(
          cls.checkpoint_name     ,						src_lang="en"     ,						tgt_lang="fr"       )
      _lowerCAmelCase   :					List[str]        =    1
      return cls

 def    __magic_name__       (		self :	int       ):






      '''simple docstring'''




      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    __magic_name__       (		self :	List[str]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Any        =    self.tokenizer.get_vocab()
      self.assertEqual(len(A_       )     ,						self.tokenizer.vocab_size       )
      self.assertEqual(vocab["<unk>"]     ,						3       )
      self.assertIn(self.tokenizer.get_lang_token("en"       )     ,						A_       )

 def    __magic_name__       (		self :	str       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[Any]        =    "en"
      _lowerCAmelCase   :					str        =    self.tokenizer.batch_encode_plus(self.src_text       ).input_ids[0]
      self.assertListEqual(self.expected_src_tokens     ,						A_       )

 def    __magic_name__       (		self :	Optional[int]       ):






      '''simple docstring'''




      self.assertIn(A_     ,						self.tokenizer.all_special_ids       )
      # fmt: off
      _lowerCAmelCase   :					Union[str, Any]        =    [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
      _lowerCAmelCase   :					Tuple        =    self.tokenizer.decode(A_     ,						skip_special_tokens=A_       )
      _lowerCAmelCase   :					List[str]        =    self.tokenizer.decode(generated_ids[1:]     ,						skip_special_tokens=A_       )
      self.assertEqual(A_     ,						A_       )
      self.assertNotIn(self.tokenizer.eos_token     ,						A_       )

 def    __magic_name__       (		self :	Optional[int]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[Any]        =    tempfile.mkdtemp()
      _lowerCAmelCase   :					Tuple        =    self.tokenizer.lang_token_to_id
      self.tokenizer.save_pretrained(A_       )
      _lowerCAmelCase   :					Optional[int]        =    MaMaaaTokenizer.from_pretrained(A_       )
      self.assertDictEqual(new_tok.lang_token_to_id     ,						A_       )

 @require_torch
 def    __magic_name__       (		self :	Any       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[Any]        =    "en"
      _lowerCAmelCase   :					Optional[int]        =    "fr"

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

      _lowerCAmelCase   :					Union[str, Any]        =    shift_tokens_right(
          batch["labels"]     ,						self.tokenizer.pad_token_id     ,						self.tokenizer.eos_token_id       )

      for k in batch:
           _lowerCAmelCase   :					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    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					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]       )

      _lowerCAmelCase   :					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    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					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       )]       )

      _lowerCAmelCase   :					Tuple        =    "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    __magic_name__       (		self :	int       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Dict        =    self.tokenizer._build_translation_inputs("A test"     ,						return_tensors="pt"     ,						src_lang="en"     ,						tgt_lang="ar"       )

      self.assertEqual(
          nested_simplify(A_       )     ,						{
              # 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,
          }     ,						)









from typing import Dict

import numpy as np
import torch

from . import residue_constants as rc
from .tensor_utils import tensor_tree_map, tree_map







def 	_snake_case		(    SCREAMING_SNAKE_CASE				)       ->      Dict[str, torch.Tensor]:

     """simple docstring"""







     _lowerCAmelCase   :					int        =    []
     _lowerCAmelCase   :					Tuple        =    []
     _lowerCAmelCase   :					List[Any]        =    []

     for rt in rc.restypes:
          _lowerCAmelCase   :					int        =    rc.restype_name_to_atomaa_names[rc.restype_atoa[rt]]
          restype_atomaa_to_atomaa_list.append([(rc.atom_order[name] if name else 0) for name in atom_names]				)
          _lowerCAmelCase   :					str        =    {name: i for i, name in enumerate(SCREAMING_SNAKE_CASE				)}
          restype_atomaa_to_atomaa_list.append(
              [(atom_name_to_idxaa[name] if name in atom_name_to_idxaa else 0) for name in rc.atom_types]				)

          restype_atomaa_mask_list.append([(1.0 if name else 0.0) for name in atom_names]				)

     # Add dummy mapping for restype 'UNK'
     restype_atomaa_to_atomaa_list.append([0] * 14				)
     restype_atomaa_to_atomaa_list.append([0] * 37				)
     restype_atomaa_mask_list.append([0.0] * 14				)

     _lowerCAmelCase   :					List[str]        =    torch.tensor(
         SCREAMING_SNAKE_CASE		,							dtype=torch.intaa		,							device=protein["aatype"].device		,							)
     _lowerCAmelCase   :					str        =    torch.tensor(
         SCREAMING_SNAKE_CASE		,							dtype=torch.intaa		,							device=protein["aatype"].device		,							)
     _lowerCAmelCase   :					Optional[Any]        =    torch.tensor(
         SCREAMING_SNAKE_CASE		,							dtype=torch.floataa		,							device=protein["aatype"].device		,							)
     _lowerCAmelCase   :					List[str]        =    protein["aatype"].to(torch.long				)

     # create the mapping for (residx, atom14) --> atom37, i.e. an array
     # with shape (num_res, 14) containing the atom37 indices for this protein
     _lowerCAmelCase   :					Dict        =    restype_atomaa_to_atomaa[protein_aatype]
     _lowerCAmelCase   :					Optional[Any]        =    restype_atomaa_mask[protein_aatype]

     _lowerCAmelCase   :					Any        =    residx_atomaa_mask
     _lowerCAmelCase   :					Dict        =    residx_atomaa_to_atomaa.long()

     # create the gather indices for mapping back
     _lowerCAmelCase   :					Optional[int]        =    restype_atomaa_to_atomaa[protein_aatype]
     _lowerCAmelCase   :					str        =    residx_atomaa_to_atomaa.long()

     # create the corresponding mask
     _lowerCAmelCase   :					Dict        =    torch.zeros([21, 37]		,							dtype=torch.floataa		,							device=protein["aatype"].device				)
     for restype, restype_letter in enumerate(rc.restypes				):
          _lowerCAmelCase   :					Optional[Any]        =    rc.restype_atoa[restype_letter]
          _lowerCAmelCase   :					int        =    rc.residue_atoms[restype_name]
          for atom_name in atom_names:
               _lowerCAmelCase   :					Union[str, Any]        =    rc.atom_order[atom_name]
               _lowerCAmelCase   :					Dict        =    1

     _lowerCAmelCase   :					Tuple        =    restype_atomaa_mask[protein_aatype]
     _lowerCAmelCase   :					List[str]        =    residx_atomaa_mask

     return protein







def 	_snake_case		(    SCREAMING_SNAKE_CASE				)       ->      Dict[str, np.ndarray]:

     """simple docstring"""







     _lowerCAmelCase   :					Any        =    tree_map(lambda SCREAMING_SNAKE_CASE				: torch.tensor(SCREAMING_SNAKE_CASE		,							device=batch["aatype"].device				)		,							SCREAMING_SNAKE_CASE		,							np.ndarray				)
     _lowerCAmelCase   :					Optional[int]        =    tensor_tree_map(lambda SCREAMING_SNAKE_CASE				: np.array(SCREAMING_SNAKE_CASE				)		,							make_atomaa_masks(SCREAMING_SNAKE_CASE				)				)
     return out






