






import os
import re
from shutil import copyfile
from typing import List, Optional, Tuple

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


__snake_case      :      str             =       logging.get_logger(__name__)

__snake_case      :      Optional[int]             =       {
    """vocab_file""": """vocab.txt""",
    """merges_file""": """bpe.codes""",
}

__snake_case      :      str             =       {
    """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""",
    },
}

__snake_case      :      List[str]             =       {
    """vinai/phobert-base""": 2_56,
    """vinai/phobert-large""": 2_56,
}







def 		_UpperCamelCase				(      UpperCamelCase_    :   Dict						)					->				Optional[Any]:

						"""simple docstring"""



						lowerCAmelCase__        =  set()
						lowerCAmelCase__        =  word[0]
						for char in word[1:]:
												pairs.add((prev_char, char)						)
												lowerCAmelCase__        =  char

						lowerCAmelCase__        =  set(UpperCamelCase_						)
						return pairs


class       __SCREAMING_SNAKE_CASE   (				__lowercase):
						_SCREAMING_SNAKE_CASE		:    Union[str, Any]						=   VOCAB_FILES_NAMES
						_SCREAMING_SNAKE_CASE		:    Tuple						=   PRETRAINED_VOCAB_FILES_MAP
						_SCREAMING_SNAKE_CASE		:    Tuple						=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES






						def __init__(		self       ,  _UpperCamelCase       ,  _UpperCamelCase       ,  _UpperCamelCase="<s>"       ,  _UpperCamelCase="</s>"       ,  _UpperCamelCase="</s>"       ,  _UpperCamelCase="<s>"       ,  _UpperCamelCase="<unk>"       ,  _UpperCamelCase="<pad>"       ,  _UpperCamelCase="<mask>"       ,  **_UpperCamelCase       ,  ):






												"""simple docstring"""
												super().__init__(
												    bos_token=_UpperCamelCase       ,  eos_token=_UpperCamelCase       ,  unk_token=_UpperCamelCase       ,  sep_token=_UpperCamelCase       ,  cls_token=_UpperCamelCase       ,  pad_token=_UpperCamelCase       ,  mask_token=_UpperCamelCase       ,  **_UpperCamelCase       ,  )

												lowerCAmelCase__        =  vocab_file
												lowerCAmelCase__        =  merges_file

												lowerCAmelCase__        =  {}
												lowerCAmelCase__        =  0
												lowerCAmelCase__        =  1
												lowerCAmelCase__        =  2
												lowerCAmelCase__        =  3

												self.add_from_file(_UpperCamelCase				)

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

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






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase = None				):






												"""simple docstring"""

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






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase = None       ,  _UpperCamelCase = False				):






												"""simple docstring"""

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

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






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase = None				):






												"""simple docstring"""
												lowerCAmelCase__        =  [self.sep_token_id]
												lowerCAmelCase__        =  [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				):






												"""simple docstring"""
												return len(self.encoder				)






						def  UpperCamelCase__ (		self				):






												"""simple docstring"""
												return dict(self.encoder       ,  **self.added_tokens_encoder				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												if token in self.cache:
																		return self.cache[token]
												lowerCAmelCase__        =  tuple(_UpperCamelCase				)
												lowerCAmelCase__        =  tuple(list(word[:-1]				) + [word[-1] + '</w>']				)
												lowerCAmelCase__        =  get_pairs(_UpperCamelCase				)

												if not pairs:
																		return token

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

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






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  []

												lowerCAmelCase__        =  re.findall(r'\S+\n?'       ,  _UpperCamelCase				)

												for token in words:
																		split_tokens.extend(list(self.bpe(_UpperCamelCase				).split(' '				)				)				)
												return split_tokens






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												return self.encoder.get(_UpperCamelCase       ,  self.encoder.get(self.unk_token				)				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												return self.decoder.get(_UpperCamelCase       ,  self.unk_token				)






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												lowerCAmelCase__        =  ' '.join(_UpperCamelCase				).replace('@@ '       ,  ''				).strip()
												return out_string






						def  UpperCamelCase__ (		self       ,  _UpperCamelCase       ,  _UpperCamelCase = None				):






												"""simple docstring"""
												if not os.path.isdir(_UpperCamelCase				):
																		logger.error(F"Vocabulary path ({save_directory}) should be a directory"				)
																		return
												lowerCAmelCase__        =  os.path.join(
												    _UpperCamelCase       ,  (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']				)
												lowerCAmelCase__        =  os.path.join(
												    _UpperCamelCase       ,  (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']				)

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

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

												return out_vocab_file, out_merge_file







						def  UpperCamelCase__ (		self       ,  _UpperCamelCase				):






												"""simple docstring"""
												if isinstance(_UpperCamelCase       ,  _UpperCamelCase				):
																		try:
																								with open(_UpperCamelCase       ,  'r'       ,  encoding='utf-8'				) as fd:
																														self.add_from_file(_UpperCamelCase				)
																		except FileNotFoundError as fnfe:
																								raise fnfe
																		except UnicodeError:
																								raise Exception(F"Incorrect encoding detected in {f}, please rebuild the dataset"				)
																		return

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














def 		_UpperCamelCase				(      UpperCamelCase_    :   str						)					->				str:

						"""simple docstring"""



						return " ".join(input_str.split()[::-1]						)


if __name__ == "__main__":
					import doctest

					doctest.testmod()





