

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


__lowercase     : Optional[int]       =						logging.get_logger(__name__)

__lowercase     : Optional[Any]       =						'''▁'''

__lowercase     : Union[str, Any]       =						{'''vocab_file''': '''sentencepiece.bpe.model'''}

__lowercase     : Optional[Any]       =						{
    '''vocab_file''': {
        '''xlm-roberta-base''': '''https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model''',
        '''xlm-roberta-large''': '''https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model''',
        '''xlm-roberta-large-finetuned-conll02-dutch''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model'''
        ),
        '''xlm-roberta-large-finetuned-conll02-spanish''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model'''
        ),
        '''xlm-roberta-large-finetuned-conll03-english''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model'''
        ),
        '''xlm-roberta-large-finetuned-conll03-german''': (
            '''https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model'''
        ),
    }
}

__lowercase     : Optional[Any]       =						{
    '''xlm-roberta-base''': 512,
    '''xlm-roberta-large''': 512,
    '''xlm-roberta-large-finetuned-conll02-dutch''': 512,
    '''xlm-roberta-large-finetuned-conll02-spanish''': 512,
    '''xlm-roberta-large-finetuned-conll03-english''': 512,
    '''xlm-roberta-large-finetuned-conll03-german''': 512,
}



class 						_A     (				snake_case				):





  '''simple docstring'''



  __lowerCamelCase			:      str					=   VOCAB_FILES_NAMES
  __lowerCamelCase			:      int					=   PRETRAINED_VOCAB_FILES_MAP
  __lowerCamelCase			:      Optional[int]					=   PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  __lowerCamelCase			:      Optional[Any]					=   ['''input_ids''', '''attention_mask''']





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

      '''simple docstring'''
      # Mask token behave like a normal word, i.e. include the space before it
      snake_case							:		Tuple        =		AddedToken(SCREAMING_SNAKE_CASE_   ,lstrip=SCREAMING_SNAKE_CASE_   ,rstrip=SCREAMING_SNAKE_CASE_    ) if isinstance(SCREAMING_SNAKE_CASE_   ,SCREAMING_SNAKE_CASE_    ) else mask_token

      snake_case							:		List[str]        =		{} if sp_model_kwargs is None else sp_model_kwargs

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

      snake_case							:		Dict        =		spm.SentencePieceProcessor(**self.sp_model_kwargs    )
      self.sp_model.Load(str(SCREAMING_SNAKE_CASE_    )    )
      snake_case							:		List[Any]        =		vocab_file

      # Original fairseq vocab and spm vocab must be "aligned":
      # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
      # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
      # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
      # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

      # Mimic fairseq token-to-id alignment for the first 4 token
      snake_case							:		str        =		{"""<s>""": 0, """<pad>""": 1, """</s>""": 2, """<unk>""": 3}

      # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
      snake_case							:		str        =		1

      snake_case							:		List[Any]        =		len(self.sp_model    ) + self.fairseq_offset
      snake_case							:		List[str]        =		{v: k for k, v in self.fairseq_tokens_to_ids.items()}





  def __getstate__(  self    ):

      '''simple docstring'''
      snake_case							:		Union[str, Any]        =		self.__dict__.copy()
      snake_case							:		List[Any]        =		None
      snake_case							:		int        =		self.sp_model.serialized_model_proto()
      return state





  def __setstate__(  self   ,SCREAMING_SNAKE_CASE_    ):

      '''simple docstring'''
      snake_case							:		Any        =		d

      # for backward compatibility
      if not hasattr(self   ,"""sp_model_kwargs"""    ):
          snake_case							:		Optional[Any]        =		{}

      snake_case							:		Optional[Any]        =		spm.SentencePieceProcessor(**self.sp_model_kwargs    )
      self.sp_model.LoadFromSerializedProto(self.sp_model_proto    )





  def    snake_case_       (  self   ,SCREAMING_SNAKE_CASE_   ,SCREAMING_SNAKE_CASE_ = None    ):

      '''simple docstring'''

      if token_ids_a is None:
          return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
      snake_case							:		Any        =		[self.cls_token_id]
      snake_case							:		Union[str, Any]        =		[self.sep_token_id]
      return cls + token_ids_a + sep + sep + token_ids_a + sep





  def    snake_case_       (  self   ,SCREAMING_SNAKE_CASE_   ,SCREAMING_SNAKE_CASE_ = None   ,SCREAMING_SNAKE_CASE_ = False    ):

      '''simple docstring'''

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

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





  def    snake_case_       (  self   ,SCREAMING_SNAKE_CASE_   ,SCREAMING_SNAKE_CASE_ = None    ):

      '''simple docstring'''
      snake_case							:		Union[str, Any]        =		[self.sep_token_id]
      snake_case							:		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 + sep + token_ids_a + sep    ) * [0]





  @property
  def    snake_case_       (  self    ):

      '''simple docstring'''
      return len(self.sp_model    ) + self.fairseq_offset + 1  # Add the <mask> token





  def    snake_case_       (  self    ):

      '''simple docstring'''
      snake_case							:		Union[str, Any]        =		{self.convert_ids_to_tokens(SCREAMING_SNAKE_CASE_    ): i for i in range(self.vocab_size    )}
      vocab.update(self.added_tokens_encoder    )
      return vocab





  def    snake_case_       (  self   ,SCREAMING_SNAKE_CASE_    ):

      '''simple docstring'''
      return self.sp_model.encode(SCREAMING_SNAKE_CASE_   ,out_type=SCREAMING_SNAKE_CASE_    )





  def    snake_case_       (  self   ,SCREAMING_SNAKE_CASE_    ):

      '''simple docstring'''
      if token in self.fairseq_tokens_to_ids:
          return self.fairseq_tokens_to_ids[token]
      snake_case							:		str        =		self.sp_model.PieceToId(SCREAMING_SNAKE_CASE_    )

      # Need to return unknown token if the SP model returned 0
      return spm_id + self.fairseq_offset if spm_id else self.unk_token_id





  def    snake_case_       (  self   ,SCREAMING_SNAKE_CASE_    ):

      '''simple docstring'''
      if index in self.fairseq_ids_to_tokens:
          return self.fairseq_ids_to_tokens[index]
      return self.sp_model.IdToPiece(index - self.fairseq_offset    )





  def    snake_case_       (  self   ,SCREAMING_SNAKE_CASE_    ):

      '''simple docstring'''
      snake_case							:		List[str]        =		"""""".join(SCREAMING_SNAKE_CASE_    ).replace(SCREAMING_SNAKE_CASE_   ,""" """    ).strip()
      return out_string





  def    snake_case_       (  self   ,SCREAMING_SNAKE_CASE_   ,SCREAMING_SNAKE_CASE_ = None    ):

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

      if os.path.abspath(self.vocab_file    ) != os.path.abspath(SCREAMING_SNAKE_CASE_    ) and os.path.isfile(self.vocab_file    ):
          copyfile(self.vocab_file   ,SCREAMING_SNAKE_CASE_    )
      elif not os.path.isfile(self.vocab_file    ):
          with open(SCREAMING_SNAKE_CASE_   ,"""wb"""    ) as fi:
              snake_case							:		List[str]        =		self.sp_model.serialized_model_proto()
              fi.write(SCREAMING_SNAKE_CASE_    )

      return (out_vocab_file,)






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available


__snake_case				:      Optional[int]   		=			{
    """configuration_xlm""": ["""XLM_PRETRAINED_CONFIG_ARCHIVE_MAP""", """XLMConfig""", """XLMOnnxConfig"""],
    """tokenization_xlm""": ["""XLMTokenizer"""],
}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__snake_case				:      Optional[Any]   		=			[
	    """XLM_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """XLMForMultipleChoice""",
	    """XLMForQuestionAnswering""",
	    """XLMForQuestionAnsweringSimple""",
	    """XLMForSequenceClassification""",
	    """XLMForTokenClassification""",
	    """XLMModel""",
	    """XLMPreTrainedModel""",
	    """XLMWithLMHeadModel""",
	]

try:
	if not is_tf_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	__snake_case				:      Optional[Any]   		=			[
	    """TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """TFXLMForMultipleChoice""",
	    """TFXLMForQuestionAnsweringSimple""",
	    """TFXLMForSequenceClassification""",
	    """TFXLMForTokenClassification""",
	    """TFXLMMainLayer""",
	    """TFXLMModel""",
	    """TFXLMPreTrainedModel""",
	    """TFXLMWithLMHeadModel""",
	]


if TYPE_CHECKING:
	from .configuration_xlm import XLM_PRETRAINED_CONFIG_ARCHIVE_MAP, XLMConfig, XLMOnnxConfig
	from .tokenization_xlm import XLMTokenizer

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_xlm import (
		    XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
		    XLMForMultipleChoice,
		    XLMForQuestionAnswering,
		    XLMForQuestionAnsweringSimple,
		    XLMForSequenceClassification,
		    XLMForTokenClassification,
		    XLMModel,
		    XLMPreTrainedModel,
		    XLMWithLMHeadModel,
		)

	try:
		if not is_tf_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_tf_xlm import (
		    TF_XLM_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TFXLMForMultipleChoice,
		    TFXLMForQuestionAnsweringSimple,
		    TFXLMForSequenceClassification,
		    TFXLMForTokenClassification,
		    TFXLMMainLayer,
		    TFXLMModel,
		    TFXLMPreTrainedModel,
		    TFXLMWithLMHeadModel,
		)

else:
	import sys

	__snake_case				:      Union[str, Any]   		=			_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


