



"""simple docstring"""







from .dependency_versions_table import deps
from .utils.versions import require_version, require_version_core


# define which module versions we always want to check at run time
# (usually the ones defined in `install_requires` in setup.py)
#
# order specific notes:
# - tqdm must be checked before tokenizers

UpperCamelCase     =							[
    """python""",
    """tqdm""",
    """regex""",
    """requests""",
    """packaging""",
    """filelock""",
    """numpy""",
    """tokenizers""",
    """huggingface-hub""",
    """safetensors""",
    """accelerate""",
    """pyyaml""",
]

for pkg in pkgs_to_check_at_runtime:
			if pkg in deps:
						if pkg == "tokenizers":
									# must be loaded here, or else tqdm check may fail
									from .utils import is_tokenizers_available

									if not is_tokenizers_available():
												continue  # not required, check version only if installed
						elif pkg == "accelerate":
									# must be loaded here, or else tqdm check may fail
									from .utils import is_accelerate_available

									# Maybe switch to is_torch_available in the future here so that Accelerate is hard dep of
									# Transformers with PyTorch
									if not is_accelerate_available():
												continue  # not required, check version only if installed

						require_version_core(deps[pkg])
			else:
						raise ValueError(f'can\'t find {pkg} in {deps.keys()}, check dependency_versions_table.py')

def       _lowerCamelCase				(							UpperCAmelCase_ :       Optional[int],	UpperCAmelCase_ :       Dict=None     )	-> List[Any]:






	"""simple docstring"""





	require_version(deps[pkg],	UpperCAmelCase_     )







'''simple docstring'''




import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


_a					:			Tuple							=    logging.get_logger(__name__)

_a					:			Optional[int]							=    '▁'

_a					:			str							=    {'vocab_file': 'sentencepiece.bpe.model', 'monolingual_vocab_file': 'dict.txt'}

_a					:			Optional[Any]							=    {
    'vocab_file': {
        'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model',
    },
    'monolingual_vocab_file': {
        'vinai/bartpho-syllable': 'https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt',
    },
}

_a					:			Union[str, Any]							=    {'vinai/bartpho-syllable': 1_024}



class 							lowercase_						(		a			):

  '''simple docstring'''





  __lowerCAmelCase       :			Dict     	= VOCAB_FILES_NAMES
  __lowerCAmelCase       :			str     	= PRETRAINED_VOCAB_FILES_MAP
  __lowerCAmelCase       :			Any     	= PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  __lowerCAmelCase       :			int     	= ["input_ids", "attention_mask"]
  def __init__(  self ,			a_ ,			a_ ,			a_="<s>" ,			a_="</s>" ,			a_="</s>" ,			a_="<s>" ,			a_="<unk>" ,			a_="<pad>" ,			a_="<mask>" ,			a_ = None ,			**a_ ,			)				->					None:


    """simple docstring"""
    # Mask token behave like a normal word, i.e. include the space before it
    UpperCAmelCase    				=						AddedToken(a_ ,			lstrip=a_ ,			rstrip=a_  ) if isinstance(a_ ,			a_  ) else mask_token

    UpperCAmelCase    				=						{} if sp_model_kwargs is None else sp_model_kwargs

    super().__init__(
        bos_token=a_ ,			eos_token=a_ ,			unk_token=a_ ,			sep_token=a_ ,			cls_token=a_ ,			pad_token=a_ ,			mask_token=a_ ,			sp_model_kwargs=self.sp_model_kwargs ,			**a_ ,			)

    UpperCAmelCase    				=						vocab_file
    UpperCAmelCase    				=						monolingual_vocab_file
    UpperCAmelCase    				=						spm.SentencePieceProcessor(**self.sp_model_kwargs  )
    self.sp_model.Load(str(a_  )  )

    # Load the reduced vocab

    # Keep order of special tokens for backward compatibility
    UpperCAmelCase    				=						{}
    UpperCAmelCase    				=						0
    for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]:
      if str(a_  ) not in self.fairseq_tokens_to_ids:
        UpperCAmelCase    				=						cnt
        cnt += 1
    with open(a_ ,			'r' ,			encoding='utf-8'  ) as f:
      for line in f.readlines():
        UpperCAmelCase    				=						line.strip().split()[0]
        UpperCAmelCase    				=						len(self.fairseq_tokens_to_ids  )
    if str(a_  ) not in self.fairseq_tokens_to_ids:
      UpperCAmelCase    				=						len(self.fairseq_tokens_to_ids  )

    UpperCAmelCase    				=						{v: k for k, v in self.fairseq_tokens_to_ids.items()}
  def __getstate__(  self  )				->					Any:


    """simple docstring"""
    UpperCAmelCase    				=						self.__dict__.copy()
    UpperCAmelCase    				=						None
    UpperCAmelCase    				=						self.sp_model.serialized_model_proto()
    return state
  def __setstate__(  self ,			a_  )				->					int:


    """simple docstring"""
    UpperCAmelCase    				=						d

    # for backward compatibility
    if not hasattr(self ,			'sp_model_kwargs'  ):
      UpperCAmelCase    				=						{}

    UpperCAmelCase    				=						spm.SentencePieceProcessor(**self.sp_model_kwargs  )
    self.sp_model.LoadFromSerializedProto(self.sp_model_proto  )
  def     snake_case_      (  self ,			a_ ,			a_ = None  )				->					List[int]:


    """simple docstring"""

    if token_ids_a is None:
      return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
    UpperCAmelCase    				=						[self.cls_token_id]
    UpperCAmelCase    				=						[self.sep_token_id]
    return cls + token_ids_a + sep + sep + token_ids_a + sep
  def     snake_case_      (  self ,			a_ ,			a_ = None ,			a_ = False  )				->					List[int]:


    """simple docstring"""

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

    if token_ids_a is None:
      return [1] + ([0] * len(a_  )) + [1]
    return [1] + ([0] * len(a_  )) + [1, 1] + ([0] * len(a_  )) + [1]
  def     snake_case_      (  self ,			a_ ,			a_ = None  )				->					List[int]:


    """simple docstring"""
    UpperCAmelCase    				=						[self.sep_token_id]
    UpperCAmelCase    				=						[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     snake_case_      (  self  )				->					Union[str, Any]:


    """simple docstring"""
    return len(self.fairseq_ids_to_tokens  )
  def     snake_case_      (  self  )				->					int:


    """simple docstring"""
    UpperCAmelCase    				=						{self.convert_ids_to_tokens(a_  ): i for i in range(self.vocab_size  )}
    vocab.update(self.added_tokens_encoder  )
    return vocab
  def     snake_case_      (  self ,			a_  )				->					List[str]:


    """simple docstring"""
    return self.sp_model.encode(a_ ,			out_type=a_  )
  def     snake_case_      (  self ,			a_  )				->					Any:


    """simple docstring"""
    if token in self.fairseq_tokens_to_ids:
      return self.fairseq_tokens_to_ids[token]
    else:
      return self.unk_token_id
  def     snake_case_      (  self ,			a_  )				->					Dict:


    """simple docstring"""
    return self.fairseq_ids_to_tokens[index]
  def     snake_case_      (  self ,			a_  )				->					Union[str, Any]:


    """simple docstring"""
    UpperCAmelCase    				=						''.join(a_  ).replace(a_ ,			' '  ).strip()
    return out_string





  def     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
    UpperCAmelCase    				=						os.path.join(
        a_ ,			(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']  )
    UpperCAmelCase    				=						os.path.join(
        a_ ,			(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['monolingual_vocab_file'] ,			)

    if os.path.abspath(self.vocab_file  ) != os.path.abspath(a_  ) and os.path.isfile(self.vocab_file  ):
      copyfile(self.vocab_file ,			a_  )
    elif not os.path.isfile(self.vocab_file  ):
      with open(a_ ,			'wb'  ) as fi:
        UpperCAmelCase    				=						self.sp_model.serialized_model_proto()
        fi.write(a_  )

    if os.path.abspath(self.monolingual_vocab_file  ) != os.path.abspath(
        a_  ) and os.path.isfile(self.monolingual_vocab_file  ):
      copyfile(self.monolingual_vocab_file ,			a_  )
    elif not os.path.isfile(self.monolingual_vocab_file  ):
      with open(a_ ,			'w' ,			encoding='utf-8'  ) as fp:
        for token in self.fairseq_tokens_to_ids:
          if token not in self.all_special_tokens:
            fp.write(F'''{str(a_  )} \n'''  )

    return out_vocab_file, out_monolingual_vocab_file


