


'''simple docstring'''




import json
import os
import re
import warnings
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


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

__lowercase  :      List[str]      		=				{
    """source_spm""": """source.spm""",
    """target_spm""": """target.spm""",
    """vocab""": """vocab.json""",
    """target_vocab_file""": """target_vocab.json""",
    """tokenizer_config_file""": """tokenizer_config.json""",
}

__lowercase  :      int      		=				{
    """source_spm""": {
        """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/source.spm"""
    },
    """target_spm""": {
        """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/target.spm"""
    },
    """vocab""": {
        """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/vocab.json"""
    },
    """tokenizer_config_file""": {
        """Helsinki-NLP/opus-mt-en-de""": (
            """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/tokenizer_config.json"""
        )
    },
}

__lowercase  :      Optional[int]      		=				{"""Helsinki-NLP/opus-mt-en-de""": 5_12}
__lowercase  :      Any      		=				{}





class _snake_case   ( a__   ):
							"""simple docstring"""





							__a												=     VOCAB_FILES_NAMES
							__a												=     PRETRAINED_VOCAB_FILES_MAP
							__a												=     PRETRAINED_INIT_CONFIGURATION
							__a												=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							__a												=     ['''input_ids''', '''attention_mask''']
							__a												=     re.compile('''>>.+<<'''   )  # type: re.Pattern







							def __init__(   self			,				__A			,				__A			,				__A			,				__A=None			,				__A=None			,				__A=None			,				__A="<unk>"			,				__A="</s>"			,				__A="<pad>"			,				__A=512			,				__A = None			,				__A=False			,				**__A			,				)     ->None:



											"""simple docstring"""







											__lowerCamelCase		:      Optional[Any]											=					{} if sp_model_kwargs is None else sp_model_kwargs

											super().__init__(
											    # bos_token=bos_token,  unused. Start decoding with config.decoder_start_token_id
											    source_lang=__A			,				target_lang=__A			,				unk_token=__A			,				eos_token=__A			,				pad_token=__A			,				model_max_length=__A			,				sp_model_kwargs=self.sp_model_kwargs			,				target_vocab_file=__A			,				separate_vocabs=__A			,				**__A			,				)
											assert Path(__A	).exists(), f'cannot find spm source {source_spm}'

											__lowerCamelCase		:      Dict											=					separate_vocabs
											__lowerCamelCase		:      Any											=					load_json(__A	)
											if self.unk_token not in self.encoder:
															raise KeyError("<unk> token must be in vocab"	)
											assert self.pad_token in self.encoder

											if separate_vocabs:
															__lowerCamelCase		:      Union[str, Any]											=					load_json(__A	)
															__lowerCamelCase		:      Dict											=					{v: k for k, v in self.target_encoder.items()}
															__lowerCamelCase		:      Optional[int]											=					[]
											else:
															__lowerCamelCase		:      Dict											=					{v: k for k, v in self.encoder.items()}
															__lowerCamelCase		:      list											=					[k for k in self.encoder if k.startswith(">>"	) and k.endswith("<<"	)]

											__lowerCamelCase		:      List[Any]											=					source_lang
											__lowerCamelCase		:      Tuple											=					target_lang
											__lowerCamelCase		:      Union[str, Any]											=					[source_spm, target_spm]

											# load SentencePiece model for pre-processing
											__lowerCamelCase		:      List[str]											=					load_spm(__A			,				self.sp_model_kwargs	)
											__lowerCamelCase		:      List[Any]											=					load_spm(__A			,				self.sp_model_kwargs	)
											__lowerCamelCase		:      Optional[int]											=					self.spm_source
											__lowerCamelCase		:      int											=					self.encoder

											# Multilingual target side: default to using first supported language code.

											self._setup_normalizer()







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->Any:



											"""simple docstring"""







											try:
															from sacremoses import MosesPunctNormalizer

															__lowerCamelCase		:      Tuple											=					MosesPunctNormalizer(self.source_lang	).normalize
											except (ImportError, FileNotFoundError):
															warnings.warn("Recommended: pip install sacremoses."	)
															__lowerCamelCase		:      Tuple											=					lambda __A	: x







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A	)     ->str:



											"""simple docstring"""







											return self.punc_normalizer(__A	) if x else ""







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A	)     ->Union[str, Any]:



											"""simple docstring"""







											return self.current_encoder.get(__A			,				self.current_encoder[self.unk_token]	)







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A	)     ->Union[str, Any]:



											"""simple docstring"""







											__lowerCamelCase		:      List[Any]											=					self.language_code_re.match(__A	)
											__lowerCamelCase		:      list											=					[match.group(0	)] if match else []
											return code, self.language_code_re.sub(""			,				__A	)







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A	)     ->List[str]:



											"""simple docstring"""







											__lowerCamelCase						,					__lowerCamelCase		:      Optional[int]											=					self.remove_language_code(__A	)
											__lowerCamelCase		:      List[str]											=					self.current_spm.encode(__A			,				out_type=__A	)
											return code + pieces







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A	)     ->str:



											"""simple docstring"""







											return self.decoder.get(__A			,				self.unk_token	)







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A			,				**__A	)     ->List[str]:



											"""simple docstring"""







											return super().batch_decode(__A			,				**__A	)







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A			,				**__A	)     ->Tuple:



											"""simple docstring"""







											return super().decode(__A			,				**__A	)







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A	)     ->str:



											"""simple docstring"""







											__lowerCamelCase		:      str											=					self.spm_source if self._decode_use_source_tokenizer else self.spm_target
											__lowerCamelCase		:      List[str]											=					[]
											__lowerCamelCase		:      List[Any]											=					""
											for token in tokens:
															# make sure that special tokens are not decoded using sentencepiece model
															if token in self.all_special_tokens:
																			out_string += sp_model.decode_pieces(__A	) + token + " "
																			__lowerCamelCase		:      Tuple											=					[]
															else:
																			current_sub_tokens.append(__A	)
											out_string += sp_model.decode_pieces(__A	)
											return out_string.strip()







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A			,				__A=None	)     ->List[int]:



											"""simple docstring"""







											if token_ids_a is None:
															return token_ids_a + [self.eos_token_id]
											# We don't expect to process pairs, but leave the pair logic for API consistency
											return token_ids_a + token_ids_a + [self.eos_token_id]







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->Union[str, Any]:



											"""simple docstring"""







											__lowerCamelCase		:      Dict											=					self.spm_source
											__lowerCamelCase		:      Optional[Any]											=					self.encoder







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->Dict:



											"""simple docstring"""







											__lowerCamelCase		:      Union[str, Any]											=					self.spm_target
											if self.separate_vocabs:
															__lowerCamelCase		:      Optional[Any]											=					self.target_encoder







							@property
							def 		__SCREAMING_SNAKE_CASE(   self	)     ->int:



											"""simple docstring"""







											return len(self.encoder	)







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A			,				__A = None	)     ->Tuple[str]:



											"""simple docstring"""







											if not os.path.isdir(__A	):
															logger.error(f'Vocabulary path ({save_directory}) should be a directory'	)
															return
											__lowerCamelCase		:      Optional[Any]											=					[]

											if self.separate_vocabs:
															__lowerCamelCase		:      int											=					os.path.join(
															    __A			,				(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"]			,				)
															__lowerCamelCase		:      Union[str, Any]											=					os.path.join(
															    __A			,				(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["target_vocab_file"]			,				)
															save_json(self.encoder			,				__A	)
															save_json(self.target_encoder			,				__A	)
															saved_files.append(__A	)
															saved_files.append(__A	)
											else:
															__lowerCamelCase		:      int											=					os.path.join(
															    __A			,				(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab"]	)
															save_json(self.encoder			,				__A	)
															saved_files.append(__A	)

											for spm_save_filename, spm_orig_path, spm_model in zip(
											    [VOCAB_FILES_NAMES["source_spm"], VOCAB_FILES_NAMES["target_spm"]]			,				self.spm_files			,				[self.spm_source, self.spm_target]			,				):
															__lowerCamelCase		:      List[str]											=					os.path.join(
															    __A			,				(filename_prefix + "-" if filename_prefix else "") + spm_save_filename	)
															if os.path.abspath(__A	) != os.path.abspath(__A	) and os.path.isfile(__A	):
																			copyfile(__A			,				__A	)
																			saved_files.append(__A	)
															elif not os.path.isfile(__A	):
																			with open(__A			,				"wb"	) as fi:
																							__lowerCamelCase		:      List[Any]											=					spm_model.serialized_model_proto()
																							fi.write(__A	)
																			saved_files.append(__A	)

											return tuple(__A	)







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->Dict:



											"""simple docstring"""







											return self.get_src_vocab()







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->Dict:



											"""simple docstring"""







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







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->List[Any]:



											"""simple docstring"""







											return dict(self.target_encoder			,				**self.added_tokens_decoder	)







							def __getstate__(   self	)     ->Dict:



											"""simple docstring"""







											__lowerCamelCase		:      Optional[Any]											=					self.__dict__.copy()
											state.update(
											    {k: None for k in ["spm_source", "spm_target", "current_spm", "punc_normalizer", "target_vocab_file"]}	)
											return state







							def __setstate__(   self			,				__A	)     ->None:



											"""simple docstring"""







											__lowerCamelCase		:      Any											=					d

											# for backward compatibility
											if not hasattr(self			,				"sp_model_kwargs"	):
															__lowerCamelCase		:      Dict											=					{}

											__lowerCamelCase						,					__lowerCamelCase		:      Union[str, Any]											=					(load_spm(__A			,				self.sp_model_kwargs	) for f in self.spm_files)
											__lowerCamelCase		:      int											=					self.spm_source
											self._setup_normalizer()







							def 		__SCREAMING_SNAKE_CASE(   self			,				*__A			,				**__A	)     ->Union[str, Any]:



											"""simple docstring"""







											return 1







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A	)     ->List[str]:



											"""simple docstring"""







											__lowerCamelCase		:      int											=					set(self.all_special_ids	)  # call it once instead of inside list comp
											all_special_ids.remove(self.unk_token_id	)  # <unk> is only sometimes special
											return [1 if x in all_special_ids else 0 for x in seq]







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A			,				__A = None			,				__A = False	)     ->List[int]:



											"""simple docstring"""







											if already_has_special_tokens:
															return self._special_token_mask(__A	)
											elif token_ids_a is None:
															return self._special_token_mask(__A	) + [1]
											else:
															return self._special_token_mask(token_ids_a + token_ids_a	) + [1]





def 							a_       (						lowercase							,						lowercase    )			->sentencepiece.SentencePieceProcessor:






				'''simple docstring'''

				__lowerCamelCase		:      Optional[Any]											=					sentencepiece.SentencePieceProcessor(**lowercase    )
				spm.Load(lowercase    )
				return spm





def 							a_       (						lowercase							,						lowercase    )			->None:






				'''simple docstring'''

				with open(lowercase							,						"w"    ) as f:
								json.dump(lowercase							,						lowercase							,						indent=2    )





def 							a_       (						lowercase    )			->Union[Dict, List]:






				'''simple docstring'''

				with open(lowercase							,						"r"    ) as f:
								return json.load(lowercase    )









'''simple docstring'''




import unittest

from transformers import ErnieMTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


__lowercase  :      Any      		=				get_tests_dir("""fixtures/spiece.model""")





@require_sentencepiece
@require_tokenizers
class _snake_case   ( a__    ,   unittest.TestCase   ):
							"""simple docstring"""





							__a												=     ErnieMTokenizer
							__a												=     False
							__a												=     True
							__a												=     False
							__a												=     False







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->Union[str, Any]:



											"""simple docstring"""







											super().setUp()

											# We have a SentencePiece fixture for testing
											__lowerCamelCase		:      Optional[int]											=					ErnieMTokenizer(__A			,				unk_token="<unk>"			,				pad_token="<pad>"	)
											tokenizer.save_pretrained(self.tmpdirname	)







							def 		__SCREAMING_SNAKE_CASE(   self			,				__A	)     ->Optional[int]:



											"""simple docstring"""







											__lowerCamelCase		:      Optional[int]											=					"this is a test"
											__lowerCamelCase		:      List[str]											=					"this is a test"
											return input_text, output_text







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->Tuple:



											"""simple docstring"""







											__lowerCamelCase		:      Any											=					"<pad>"
											__lowerCamelCase		:      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 		__SCREAMING_SNAKE_CASE(   self	)     ->Optional[Any]:



											"""simple docstring"""







											__lowerCamelCase		:      Union[str, Any]											=					list(self.get_tokenizer().get_vocab().keys()	)

											self.assertEqual(vocab_keys[0]			,				"<pad>"	)
											self.assertEqual(vocab_keys[1]			,				"<unk>"	)
											self.assertEqual(vocab_keys[-1]			,				"▁eloquent"	)
											self.assertEqual(len(__A	)			,				30000	)







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->Dict:



											"""simple docstring"""







											self.assertEqual(self.get_tokenizer().vocab_size			,				30000	)







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->int:



											"""simple docstring"""







											if not self.test_rust_tokenizer:
															return

											__lowerCamelCase		:      Union[str, Any]											=					self.get_tokenizer()
											__lowerCamelCase		:      Optional[Any]											=					self.get_rust_tokenizer()

											__lowerCamelCase		:      Dict											=					"I was born in 92000, and this is falsé."

											__lowerCamelCase		:      str											=					tokenizer.tokenize(__A	)
											__lowerCamelCase		:      str											=					rust_tokenizer.tokenize(__A	)
											self.assertListEqual(__A			,				__A	)

											__lowerCamelCase		:      Tuple											=					tokenizer.encode(__A			,				add_special_tokens=__A	)
											__lowerCamelCase		:      Tuple											=					rust_tokenizer.encode(__A			,				add_special_tokens=__A	)
											self.assertListEqual(__A			,				__A	)

											__lowerCamelCase		:      Optional[int]											=					self.get_rust_tokenizer()
											__lowerCamelCase		:      Dict											=					tokenizer.encode(__A	)
											__lowerCamelCase		:      List[str]											=					rust_tokenizer.encode(__A	)
											self.assertListEqual(__A			,				__A	)







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->Optional[int]:



											"""simple docstring"""







											__lowerCamelCase		:      Tuple											=					ErnieMTokenizer(__A			,				do_lower_case=__A			,				unk_token="<unk>"			,				pad_token="<pad>"	)

											__lowerCamelCase		:      Optional[Any]											=					tokenizer.tokenize("This is a test"	)
											self.assertListEqual(__A			,				["▁this", "▁is", "▁a", "▁test"]	)

											self.assertListEqual(tokenizer.convert_tokens_to_ids(__A	)			,				[48, 25, 21, 1289]	)

											__lowerCamelCase		:      Any											=					tokenizer.tokenize("I was born in 92000, and this is falsé."	)
											# ErnieMTokenizer(paddlenlp implementation) outputs '9' instead of '_9' so to mimic that '_9' is changed to '9'
											self.assertListEqual(
											    __A			,				["▁i", "▁was", "▁born", "▁in", "9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", "."]	)
											__lowerCamelCase		:      Optional[int]											=					tokenizer.convert_tokens_to_ids(__A	)
											self.assertListEqual(__A			,				[31, 23, 386, 19, 518, 3050, 15, 17, 48, 25, 8256, 18, 1, 9]	)

											__lowerCamelCase		:      Dict											=					tokenizer.convert_ids_to_tokens(__A	)
											self.assertListEqual(
											    __A			,				["▁i", "▁was", "▁born", "▁in", "9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "."]			,				)







							def 		__SCREAMING_SNAKE_CASE(   self	)     ->Tuple:



											"""simple docstring"""







											__lowerCamelCase		:      Union[str, Any]											=					ErnieMTokenizer(__A			,				unk_token="<unk>"			,				pad_token="<pad>"	)

											__lowerCamelCase		:      int											=					tokenizer.encode("sequence builders"	)
											__lowerCamelCase		:      List[Any]											=					tokenizer.encode("multi-sequence build"	)

											__lowerCamelCase		:      Tuple											=					tokenizer.build_inputs_with_special_tokens(__A	)
											__lowerCamelCase		:      Optional[int]											=					tokenizer.build_inputs_with_special_tokens(__A			,				__A	)

											assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
											assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + [
											    tokenizer.sep_token_id
											] + text_a + [tokenizer.sep_token_id]







							@slow
							def 		__SCREAMING_SNAKE_CASE(   self	)     ->int:



											"""simple docstring"""







											__lowerCamelCase		:      Tuple											=					{"input_ids": [[0, 11062, 82772, 7, 15, 82772, 538, 51529, 237, 17198, 1290, 206, 9, 215175, 1314, 136, 17198, 1290, 206, 9, 56359, 42, 122009, 9, 16466, 16, 87344, 4537, 9, 4717, 78381, 6, 159958, 7, 15, 24480, 618, 4, 527, 22693, 9, 304, 4, 2777, 24480, 9874, 4, 43523, 594, 4, 803, 18392, 33189, 18, 4, 43523, 24447, 5, 5, 5, 16, 100, 24955, 83658, 9626, 144057, 15, 839, 22335, 16, 136, 24955, 83658, 83479, 15, 39102, 724, 16, 678, 645, 6460, 1328, 4589, 42, 122009, 115774, 23, 3559, 1328, 46876, 7, 136, 53894, 1940, 42227, 41159, 17721, 823, 425, 4, 27512, 98722, 206, 136, 5531, 4970, 919, 17336, 5, 2], [0, 20080, 618, 83, 82775, 47, 479, 9, 1517, 73, 53894, 333, 80581, 110117, 18811, 5256, 1295, 51, 152526, 297, 7986, 390, 124416, 538, 35431, 214, 98, 15044, 25737, 136, 7108, 43701, 23, 756, 135355, 7, 5, 2, 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, 581, 63773, 119455, 6, 147797, 88203, 7, 645, 70, 21, 3285, 10269, 5, 2, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}
											# fmt: on

											self.tokenizer_integration_test_util(
											    expected_encoding=__A			,				model_name="susnato/ernie-m-base_pytorch"			,				sequences=[
											        "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides "
											        "general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural "
											        "Language Understanding (NLU) and Natural Language Generation (NLG) with over32+ pretrained "
											        "models in100+ languages and deep interoperability between Jax, PyTorch and TensorFlow.",
											        "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly "
											        "conditioning on both left and right context in all layers.",
											        "The quick brown fox jumps over the lazy dog.",
											    ]			,				)





