


'''simple docstring'''
import os
import re
from shutil import copyfile
from typing import List, Optional, Tuple

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


__SCREAMING_SNAKE_CASE					:				Tuple									=		logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE					:				List[str]									=		{
    '''vocab_file''': '''vocab.txt''',
    '''merges_file''': '''bpe.codes''',
}

__SCREAMING_SNAKE_CASE					:				Any									=		{
    '''vocab_file''': {
        '''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt''',
        '''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt''',
    },
    '''merges_file''': {
        '''vinai/phobert-base''': '''https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes''',
        '''vinai/phobert-large''': '''https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes''',
    },
}

__SCREAMING_SNAKE_CASE					:				Optional[Any]									=		{
    '''vinai/phobert-base''': 256,
    '''vinai/phobert-large''': 256,
}







def       a_				(	UpperCamelCase_ ):
							A_			    =		set()
							A_			    =		word[0]
							for char in word[1:]:
														pairs.add((prev_char, char) )
														A_			    =		char

							A_			    =		set(UpperCamelCase_ )
							return pairs







class 					__lowerCAmelCase   (   lowercase						):

						"""simple docstring"""






						_UpperCAmelCase		:       List[str]   						=VOCAB_FILES_NAMES
						_UpperCAmelCase		:       Union[str, Any]   						=PRETRAINED_VOCAB_FILES_MAP
						_UpperCAmelCase		:       Any   						=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES






						def __init__(  self							:      Any ,  lowerCAmelCase							:      str ,  lowerCAmelCase							:      Optional[int] ,  lowerCAmelCase							:      Optional[Any]="<s>" ,  lowerCAmelCase							:      Any="</s>" ,  lowerCAmelCase							:      Optional[int]="</s>" ,  lowerCAmelCase							:      Tuple="<s>" ,  lowerCAmelCase							:      Union[str, Any]="<unk>" ,  lowerCAmelCase							:      Tuple="<pad>" ,  lowerCAmelCase							:      Optional[Any]="<mask>" ,  **lowerCAmelCase							:      str ,  ):
													super().__init__(
													    bos_token=lowerCAmelCase ,  eos_token=lowerCAmelCase ,  unk_token=lowerCAmelCase ,  sep_token=lowerCAmelCase ,  cls_token=lowerCAmelCase ,  pad_token=lowerCAmelCase ,  mask_token=lowerCAmelCase ,  **lowerCAmelCase ,  )

													A_			    =		vocab_file
													A_			    =		merges_file

													A_			    =		{}
													A_			    =		0
													A_			    =		1
													A_			    =		2
													A_			    =		3

													self.add_from_file(lowerCAmelCase	)

													A_			    =		{v: k for k, v in self.encoder.items()}

													with open(lowerCAmelCase ,  encoding="utf-8"	) as merges_handle:
																				A_			    =		merges_handle.read().split("\n"	)[:-1]
													A_			    =		[tuple(merge.split()[:-1]	) for merge in merges]
													A_			    =		dict(zip(lowerCAmelCase ,  range(len(lowerCAmelCase	)	)	)	)
													A_			    =		{}






						def 				_UpperCAmelCase       (  self							:      List[Any] ,  lowerCAmelCase							:      List[int] ,  lowerCAmelCase							:      Optional[List[int]] = None	):

													if token_ids_a is None:
																				return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
													A_			    =		[self.cls_token_id]
													A_			    =		[self.sep_token_id]
													return cls + token_ids_a + sep + sep + token_ids_a + sep






						def 				_UpperCAmelCase       (  self							:      Optional[int] ,  lowerCAmelCase							:      List[int] ,  lowerCAmelCase							:      Optional[List[int]] = None ,  lowerCAmelCase							:      bool = False	):

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

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






						def 				_UpperCAmelCase       (  self							:      Any ,  lowerCAmelCase							:      List[int] ,  lowerCAmelCase							:      Optional[List[int]] = None	):
													A_			    =		[self.sep_token_id]
													A_			    =		[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]






						@property
						def 				_UpperCAmelCase       (  self							:      int	):
													return len(self.encoder	)






						def 				_UpperCAmelCase       (  self							:      str	):
													return dict(self.encoder ,  **self.added_tokens_encoder	)






						def 				_UpperCAmelCase       (  self							:      List[Any] ,  lowerCAmelCase							:      Optional[Any]	):
													if token in self.cache:
																				return self.cache[token]
													A_			    =		tuple(lowerCAmelCase	)
													A_			    =		tuple(list(word[:-1]	) + [word[-1] + "</w>"]	)
													A_			    =		get_pairs(lowerCAmelCase	)

													if not pairs:
																				return token

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

																											if word[i] == first and i < len(lowerCAmelCase	) - 1 and word[i + 1] == second:
																																		new_word.append(first + second	)
																																		i += 2
																											else:
																																		new_word.append(word[i]	)
																																		i += 1
																				A_			    =		tuple(lowerCAmelCase	)
																				A_			    =		new_word
																				if len(lowerCAmelCase	) == 1:
																											break
																				else:
																											A_			    =		get_pairs(lowerCAmelCase	)
													A_			    =		"@@ ".join(lowerCAmelCase	)
													A_			    =		word[:-4]
													A_			    =		word
													return word






						def 				_UpperCAmelCase       (  self							:      List[str] ,  lowerCAmelCase							:      Tuple	):
													A_			    =		[]

													A_			    =		re.findall(r"\S+\n?" ,  lowerCAmelCase	)

													for token in words:
																				split_tokens.extend(list(self.bpe(lowerCAmelCase	).split(" "	)	)	)
													return split_tokens






						def 				_UpperCAmelCase       (  self							:      Tuple ,  lowerCAmelCase							:      str	):
													return self.encoder.get(lowerCAmelCase ,  self.encoder.get(self.unk_token	)	)






						def 				_UpperCAmelCase       (  self							:      Tuple ,  lowerCAmelCase							:      List[str]	):
													return self.decoder.get(lowerCAmelCase ,  self.unk_token	)






						def 				_UpperCAmelCase       (  self							:      List[str] ,  lowerCAmelCase							:      List[str]	):
													A_			    =		" ".join(lowerCAmelCase	).replace("@@ " ,  ""	).strip()
													return out_string






						def 				_UpperCAmelCase       (  self							:      Tuple ,  lowerCAmelCase							:      str ,  lowerCAmelCase							:      Optional[str] = None	):
													if not os.path.isdir(lowerCAmelCase	):
																				logger.error(F"Vocabulary path ({save_directory}) should be a directory"	)
																				return
													A_			    =		os.path.join(
													    lowerCAmelCase ,  (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]	)
													A_			    =		os.path.join(
													    lowerCAmelCase ,  (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]	)

													if os.path.abspath(self.vocab_file	) != os.path.abspath(lowerCAmelCase	):
																				copyfile(self.vocab_file ,  lowerCAmelCase	)

													if os.path.abspath(self.merges_file	) != os.path.abspath(lowerCAmelCase	):
																				copyfile(self.merges_file ,  lowerCAmelCase	)

													return out_vocab_file, out_merge_file






						def 				_UpperCAmelCase       (  self							:      Optional[int] ,  lowerCAmelCase							:      int	):
													if isinstance(lowerCAmelCase ,  lowerCAmelCase	):
																				try:
																											with open(lowerCAmelCase ,  "r" ,  encoding="utf-8"	) as fd:
																																		self.add_from_file(lowerCAmelCase	)
																				except FileNotFoundError as fnfe:
																											raise fnfe
																				except UnicodeError:
																											raise Exception(F"Incorrect encoding detected in {f}, please rebuild the dataset"	)
																				return

													A_			    =		f.readlines()
													for lineTmp in lines:
																				A_			    =		lineTmp.strip()
																				A_			    =		line.rfind(" "	)
																				if idx == -1:
																											raise ValueError("Incorrect dictionary format, expected '<token> <cnt>'"	)
																				A_			    =		line[:idx]
																				A_			    =		len(self.encoder	)









'''simple docstring'''
import unittest

from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow


if is_flax_available():
							import jax

							from transformers.models.auto.modeling_flax_auto import FlaxAutoModel
							from transformers.models.bert.modeling_flax_bert import FlaxBertModel
							from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel






@require_flax
class 					__lowerCAmelCase   (   unittest.TestCase						):

						"""simple docstring"""






						@slow
						def 				_UpperCAmelCase       (  self							:      Dict	):
													for model_name in ["bert-base-cased", "bert-large-uncased"]:
																				with self.subTest(lowerCAmelCase	):
																											A_			    =		AutoConfig.from_pretrained(lowerCAmelCase	)
																											self.assertIsNotNone(lowerCAmelCase	)
																											self.assertIsInstance(lowerCAmelCase ,  lowerCAmelCase	)

																											A_			    =		FlaxAutoModel.from_pretrained(lowerCAmelCase	)
																											self.assertIsNotNone(lowerCAmelCase	)
																											self.assertIsInstance(lowerCAmelCase ,  lowerCAmelCase	)






						@slow
						def 				_UpperCAmelCase       (  self							:      Union[str, Any]	):
													for model_name in ["roberta-base", "roberta-large"]:
																				with self.subTest(lowerCAmelCase	):
																											A_			    =		AutoConfig.from_pretrained(lowerCAmelCase	)
																											self.assertIsNotNone(lowerCAmelCase	)
																											self.assertIsInstance(lowerCAmelCase ,  lowerCAmelCase	)

																											A_			    =		FlaxAutoModel.from_pretrained(lowerCAmelCase	)
																											self.assertIsNotNone(lowerCAmelCase	)
																											self.assertIsInstance(lowerCAmelCase ,  lowerCAmelCase	)






						@slow
						def 				_UpperCAmelCase       (  self							:      List[Any]	):
													for model_name in ["bert-base-cased", "bert-large-uncased"]:
																				A_			    =		AutoTokenizer.from_pretrained(lowerCAmelCase	)
																				A_			    =		FlaxBertModel.from_pretrained(lowerCAmelCase	)
																				A_			    =		tokenizer("Do you support jax jitted function?" ,  return_tensors=TensorType.JAX	)

																				@jax.jit
																				def eval(**lowerCAmelCase							:      Tuple	):
																											return model(**lowerCAmelCase	)

																				eval(**lowerCAmelCase	).block_until_ready()






						@slow
						def 				_UpperCAmelCase       (  self							:      str	):
													for model_name in ["roberta-base", "roberta-large"]:
																				A_			    =		AutoTokenizer.from_pretrained(lowerCAmelCase	)
																				A_			    =		FlaxRobertaModel.from_pretrained(lowerCAmelCase	)
																				A_			    =		tokenizer("Do you support jax jitted function?" ,  return_tensors=TensorType.JAX	)

																				@jax.jit
																				def eval(**lowerCAmelCase							:      Any	):
																											return model(**lowerCAmelCase	)

																				eval(**lowerCAmelCase	).block_until_ready()






						def 				_UpperCAmelCase       (  self							:      List[Any]	):
													with self.assertRaisesRegex(
													    lowerCAmelCase ,  "bert-base is not a local folder and is not a valid model identifier"	):
																				A_			    =		FlaxAutoModel.from_pretrained("bert-base"	)






						def 				_UpperCAmelCase       (  self							:      Any	):
													with self.assertRaisesRegex(
													    lowerCAmelCase ,  r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"	):
																				A_			    =		FlaxAutoModel.from_pretrained(lowerCAmelCase ,  revision="aaaaaa"	)






						def 				_UpperCAmelCase       (  self							:      Dict	):
													with self.assertRaisesRegex(
													    lowerCAmelCase ,  "hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack" ,  ):
																				A_			    =		FlaxAutoModel.from_pretrained("hf-internal-testing/config-no-model"	)






						def 				_UpperCAmelCase       (  self							:      Any	):
													with self.assertRaisesRegex(lowerCAmelCase ,  "Use `from_pt=True` to load this model"	):
																				A_			    =		FlaxAutoModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only"	)





