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

from transformers import BatchEncoding, MarianTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow
from transformers.utils import is_sentencepiece_available, is_tf_available, is_torch_available


if is_sentencepiece_available():
		from transformers.models.marian.tokenization_marian import VOCAB_FILES_NAMES, save_json

from ...test_tokenization_common import TokenizerTesterMixin


__lowerCamelCase					:	Tuple       =  get_tests_dir('''fixtures/test_sentencepiece.model''')

__lowerCamelCase					:	Optional[Any]       =  {'''target_lang''': '''fi''', '''source_lang''': '''en'''}
__lowerCamelCase					:	Any       =  '''>>zh<<'''
__lowerCamelCase					:	str       =  '''Helsinki-NLP/'''

if is_torch_available():
		__lowerCamelCase					:	List[Any]       =  '''pt'''
elif is_tf_available():
		__lowerCamelCase					:	List[str]       =  '''tf'''
else:
		__lowerCamelCase					:	Dict       =  '''jax'''






@require_sentencepiece
class 		a__						(					A__    ,		unittest.TestCase					):
					A	       =							MarianTokenizer
					A	       =							False
					A	       =							True

					def 				__UpperCamelCase   (    self      :       Optional[Any]    ):







							"""simple docstring"""






							super().setUp()
							SCREAMING_SNAKE_CASE_  :		Dict				      =    ["</s>", "<unk>", "▁This", "▁is", "▁a", "▁t", "est", "\u0120", "<pad>"]
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    dict(zip(_A,range(len(_A    )    )    )    )
							SCREAMING_SNAKE_CASE_  :		str				      =    Path(self.tmpdirname    )
							save_json(_A,save_dir / VOCAB_FILES_NAMES["vocab"]    )
							save_json(_A,save_dir / VOCAB_FILES_NAMES["tokenizer_config_file"]    )
							if not (save_dir / VOCAB_FILES_NAMES["source_spm"]).exists():
									copyfile(_A,save_dir / VOCAB_FILES_NAMES["source_spm"]    )
									copyfile(_A,save_dir / VOCAB_FILES_NAMES["target_spm"]    )

							SCREAMING_SNAKE_CASE_  :		int				      =    MarianTokenizer.from_pretrained(self.tmpdirname    )
							tokenizer.save_pretrained(self.tmpdirname    )

					def 				__UpperCamelCase   (    self      :       Union[str, Any],**_A      :       Optional[Any]    ):







							"""simple docstring"""






							return MarianTokenizer.from_pretrained(self.tmpdirname,**_A    )

					def 				__UpperCamelCase   (    self      :       Union[str, Any],_A      :       List[str]    ):







							"""simple docstring"""






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

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







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    "</s>"
							SCREAMING_SNAKE_CASE_  :		str				      =    0

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

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







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    list(self.get_tokenizer().get_vocab().keys()    )

							self.assertEqual(vocab_keys[0],"</s>"    )
							self.assertEqual(vocab_keys[1],"<unk>"    )
							self.assertEqual(vocab_keys[-1],"<pad>"    )
							self.assertEqual(len(_A    ),9    )

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






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

					def 				__UpperCamelCase   (    self      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    MarianTokenizer.from_pretrained(F'{ORG_NAME}opus-mt-en-de'    )
							SCREAMING_SNAKE_CASE_  :		Dict				      =    en_de_tokenizer(["I am a small frog"],return_tensors=_A    )
							self.assertIsInstance(_A,_A    )
							SCREAMING_SNAKE_CASE_  :		str				      =    [38, 121, 14, 697, 3_8848, 0]
							self.assertListEqual(_A,batch.input_ids[0]    )

							SCREAMING_SNAKE_CASE_  :		str				      =    tempfile.mkdtemp()
							en_de_tokenizer.save_pretrained(_A    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    [x.name for x in Path(_A    ).glob("*"    )]
							self.assertIn("source.spm",_A    )
							MarianTokenizer.from_pretrained(_A    )

					def 				__UpperCamelCase   (    self      :       Dict    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    self.get_tokenizer()

							SCREAMING_SNAKE_CASE_  :		str				      =    tok(
							    ["I am a small frog" * 1000, "I am a small frog"],padding=_A,truncation=_A,return_tensors=_A    )
							self.assertIsInstance(_A,_A    )
							self.assertEqual(batch.input_ids.shape,(2, 512)    )

					def 				__UpperCamelCase   (    self      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		int				      =    self.get_tokenizer()
							SCREAMING_SNAKE_CASE_  :		str				      =    tok(["I am a tiny frog", "I am a small frog"],padding=_A,return_tensors=_A    )
							self.assertIsInstance(_A,_A    )
							self.assertEqual(batch_smaller.input_ids.shape,(2, 10)    )

					@slow
					def 				__UpperCamelCase   (    self      :       str    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    {"input_ids": [[4_3495, 462, 20, 4_2164, 1369, 52, 464, 132, 1703, 492, 13, 7491, 3_8999, 6, 8, 464, 132, 1703, 492, 13, 4669, 3_7867, 13, 7525, 27, 1593, 988, 13, 3_3972, 7029, 6, 20, 8251, 383, 2, 270, 5866, 3788, 2, 2353, 8251, 1_2338, 2, 1_3958, 387, 2, 3629, 6953, 188, 2900, 2, 1_3958, 8011, 1_1501, 23, 8460, 4073, 3_4009, 20, 435, 1_1439, 27, 8, 8460, 4073, 6004, 20, 9988, 375, 27, 33, 266, 1945, 1076, 1350, 3_7867, 3288, 5, 577, 1076, 4374, 8, 5082, 5, 2_6453, 257, 556, 403, 2, 242, 132, 383, 316, 492, 8, 1_0767, 6, 316, 304, 4239, 3, 0], [148, 1_5722, 19, 1839, 12, 1350, 13, 2_2327, 5082, 5418, 4_7567, 3_5938, 59, 318, 1_9552, 108, 2183, 54, 1_4976, 4835, 32, 547, 1114, 8, 315, 2417, 5, 92, 1_9088, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100], [36, 6395, 1_2570, 3_9147, 1_1597, 6, 266, 4, 4_5405, 7296, 3, 0, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100, 5_8100]], "attention_mask": [[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, 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, 0, 0, 0, 0], [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]]}  # noqa: E501
							# fmt: on

							self.tokenizer_integration_test_util(
							    expected_encoding=_A,model_name="Helsinki-NLP/opus-mt-en-de",revision="1a8c2263da11e68e50938f97e10cd57820bd504c",decode_kwargs={"use_source_tokenizer": True},)






					def 				__UpperCamelCase   (    self      :       List[Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Any				      =    MarianTokenizer.from_pretrained("hf-internal-testing/test-marian-two-vocabs"    )

							SCREAMING_SNAKE_CASE_  :		Tuple				      =    "Tämä on testi"
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    "This is a test"

							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    [76, 7, 2047, 2]
							SCREAMING_SNAKE_CASE_  :		str				      =    [69, 12, 11, 940, 2]

							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    tokenizer(_A    ).input_ids
							self.assertListEqual(_A,_A    )

							SCREAMING_SNAKE_CASE_  :		Dict				      =    tokenizer(text_target=_A    ).input_ids
							self.assertListEqual(_A,_A    )

							SCREAMING_SNAKE_CASE_  :		Any				      =    tokenizer.decode(_A,skip_special_tokens=_A    )
							self.assertEqual(_A,_A    )

import json
from typing import List, Optional, Tuple

from tokenizers import normalizers
from tokenizers.pre_tokenizers import BertPreTokenizer, PreTokenizer

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_roformer import RoFormerTokenizer
from .tokenization_utils import JiebaPreTokenizer


__lowerCamelCase					:	Optional[Any]       =  logging.get_logger(__name__)

__lowerCamelCase					:	Dict       =  {'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

__lowerCamelCase					:	int       =  {
    '''vocab_file''': {
        '''junnyu/roformer_chinese_small''': '''https://huggingface.co/junnyu/roformer_chinese_small/resolve/main/vocab.txt''',
        '''junnyu/roformer_chinese_base''': '''https://huggingface.co/junnyu/roformer_chinese_base/resolve/main/vocab.txt''',
        '''junnyu/roformer_chinese_char_small''': (
            '''https://huggingface.co/junnyu/roformer_chinese_char_small/resolve/main/vocab.txt'''
        ),
        '''junnyu/roformer_chinese_char_base''': (
            '''https://huggingface.co/junnyu/roformer_chinese_char_base/resolve/main/vocab.txt'''
        ),
        '''junnyu/roformer_small_discriminator''': (
            '''https://huggingface.co/junnyu/roformer_small_discriminator/resolve/main/vocab.txt'''
        ),
        '''junnyu/roformer_small_generator''': (
            '''https://huggingface.co/junnyu/roformer_small_generator/resolve/main/vocab.txt'''
        ),
    }
}

__lowerCamelCase					:	Any       =  {
    '''junnyu/roformer_chinese_small''': 15_36,
    '''junnyu/roformer_chinese_base''': 15_36,
    '''junnyu/roformer_chinese_char_small''': 5_12,
    '''junnyu/roformer_chinese_char_base''': 5_12,
    '''junnyu/roformer_small_discriminator''': 1_28,
    '''junnyu/roformer_small_generator''': 1_28,
}


__lowerCamelCase					:	Union[str, Any]       =  {
    '''junnyu/roformer_chinese_small''': {'''do_lower_case''': True},
    '''junnyu/roformer_chinese_base''': {'''do_lower_case''': True},
    '''junnyu/roformer_chinese_char_small''': {'''do_lower_case''': True},
    '''junnyu/roformer_chinese_char_base''': {'''do_lower_case''': True},
    '''junnyu/roformer_small_discriminator''': {'''do_lower_case''': True},
    '''junnyu/roformer_small_generator''': {'''do_lower_case''': True},
}






class 		a__						(					A__					):
					A	       =							VOCAB_FILES_NAMES
					A	       =							PRETRAINED_VOCAB_FILES_MAP
					A	       =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
					A	       =							PRETRAINED_INIT_CONFIGURATION
					A	       =							RoFormerTokenizer

					def __init__(    self      :       List[str],_A      :       int=None,_A      :       int=None,_A      :       int=True,_A      :       List[Any]="[UNK]",_A      :       Tuple="[SEP]",_A      :       List[Any]="[PAD]",_A      :       Optional[int]="[CLS]",_A      :       Optional[Any]="[MASK]",_A      :       Optional[int]=True,_A      :       List[str]=None,**_A      :       List[Any],):







							"""simple docstring"""






							super().__init__(
							    _A,tokenizer_file=_A,do_lower_case=_A,unk_token=_A,sep_token=_A,pad_token=_A,cls_token=_A,mask_token=_A,tokenize_chinese_chars=_A,strip_accents=_A,**_A,)

							SCREAMING_SNAKE_CASE_  :		Tuple				      =    json.loads(self.backend_tokenizer.normalizer.__getstate__()    )
							if (
							    pre_tok_state.get("lowercase",_A    ) != do_lower_case
							    or pre_tok_state.get("strip_accents",_A    ) != strip_accents
							):
									SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    getattr(_A,pre_tok_state.pop("type"    )    )
									SCREAMING_SNAKE_CASE_  :		Any				      =    do_lower_case
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    strip_accents
									SCREAMING_SNAKE_CASE_  :		str				      =    pre_tok_class(**_A    )

							SCREAMING_SNAKE_CASE_  :		List[str]				      =    do_lower_case

					def __getstate__(    self      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    self.__dict__.copy()
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    BertPreTokenizer()
							return state

					def __setstate__(    self      :       List[Any],_A      :       Union[str, Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		int				      =    d
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.__dict__["_tokenizer"].get_vocab()
							SCREAMING_SNAKE_CASE_  :		Any				      =    PreTokenizer.custom(JiebaPreTokenizer(_A    )    )

					def 				__UpperCamelCase   (    self      :       Union[str, Any],_A      :       List[Any],_A      :       str=None    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    [self.cls_token_id] + token_ids_a + [self.sep_token_id]

							if token_ids_a:
									output += token_ids_a + [self.sep_token_id]

							return output

					def 				__UpperCamelCase   (    self      :       str,_A      :       List[int],_A      :       Optional[List[int]] = None    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    [self.sep_token_id]
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    [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    ) * [0] + len(token_ids_a + sep    ) * [1]

					def 				__UpperCamelCase   (    self      :       int,_A      :       str,_A      :       Optional[str] = None    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self._tokenizer.model.save(_A,name=_A    )
							return tuple(_A    )






					def 				__UpperCamelCase   (    self      :       int,_A      :       Optional[int],_A      :       List[Any]=None,_A      :       Tuple=None,_A      :       str=False,**_A      :       List[Any],):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    BertPreTokenizer()
							return super().save_pretrained(_A,_A,_A,_A,**_A    )
