


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


UpperCAmelCase__   	=							logging.get_logger(__name__)

UpperCAmelCase__   	=							'''▁'''

UpperCAmelCase__   	=							{'''vocab_file''': '''sentencepiece.bpe.model'''}

UpperCAmelCase__   	=							{
    '''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'''
        ),
    }
}

UpperCAmelCase__   	=							{
    '''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       lowerCamelCase__   (       lowerCAmelCase):
     SCREAMING_SNAKE_CASE__      			=			VOCAB_FILES_NAMES
     SCREAMING_SNAKE_CASE__      			=			PRETRAINED_VOCAB_FILES_MAP
     SCREAMING_SNAKE_CASE__      			=			PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     SCREAMING_SNAKE_CASE__      			=			['''input_ids''', '''attention_mask''']





     def __init__(self		,     UpperCAmelCase		,     UpperCAmelCase="<s>"		,     UpperCAmelCase="</s>"		,     UpperCAmelCase="</s>"		,     UpperCAmelCase="<s>"		,     UpperCAmelCase="<unk>"		,     UpperCAmelCase="<pad>"		,     UpperCAmelCase="<mask>"		,     UpperCAmelCase = None		,     **UpperCAmelCase		,     )     ->   None:
      # Mask token behave like a normal word, i.e. include the space before it
      _lowercase							      =AddedToken(UpperCAmelCase		,     lstrip=UpperCAmelCase		,     rstrip=UpperCAmelCase       ) if isinstance(UpperCAmelCase		,     UpperCAmelCase       ) else mask_token

      _lowercase							      ={} if sp_model_kwargs is None else sp_model_kwargs

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

      _lowercase							      =spm.SentencePieceProcessor(**self.sp_model_kwargs       )
      self.sp_model.Load(str(UpperCAmelCase       )       )
      _lowercase							      =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
      _lowercase							      ={'''<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
      _lowercase							      =1

      _lowercase							      =len(self.sp_model       ) + self.fairseq_offset
      _lowercase							      ={v: k for k, v in self.fairseq_tokens_to_ids.items()}





     def __getstate__(self       )     ->   Optional[int]:
      _lowercase							      =self.__dict__.copy()
      _lowercase							      =None
      _lowercase							      =self.sp_model.serialized_model_proto()
      return state





     def __setstate__(self		,     UpperCAmelCase       )     ->   List[str]:
      _lowercase							      =d

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

      _lowercase							      =spm.SentencePieceProcessor(**self.sp_model_kwargs       )
      self.sp_model.LoadFromSerializedProto(self.sp_model_proto       )





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase = None       )     ->   List[int]:

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





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase = None		,     UpperCAmelCase = False       )     ->   List[int]:

      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      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase = None       )     ->   List[int]:
      _lowercase							      =[self.sep_token_id]
      _lowercase							      =[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      __A					(self       )     ->   List[Any]:
      return len(self.sp_model       ) + self.fairseq_offset + 1  # Add the <mask> token





     def      __A					(self       )     ->   Any:
      _lowercase							      ={self.convert_ids_to_tokens(UpperCAmelCase       ): i for i in range(self.vocab_size       )}
      vocab.update(self.added_tokens_encoder       )
      return vocab





     def      __A					(self		,     UpperCAmelCase       )     ->   List[str]:
      return self.sp_model.encode(UpperCAmelCase		,     out_type=UpperCAmelCase       )





     def      __A					(self		,     UpperCAmelCase       )     ->   Union[str, Any]:
      if token in self.fairseq_tokens_to_ids:
       return self.fairseq_tokens_to_ids[token]
      _lowercase							      =self.sp_model.PieceToId(UpperCAmelCase       )

      # 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      __A					(self		,     UpperCAmelCase       )     ->   str:
      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      __A					(self		,     UpperCAmelCase       )     ->   List[Any]:
      _lowercase							      =''''''.join(UpperCAmelCase       ).replace(UpperCAmelCase		,     ''' '''       ).strip()
      return out_string





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase = None       )     ->   Tuple[str]:
      if not os.path.isdir(UpperCAmelCase       ):
       logger.error(f"Vocabulary path ({save_directory}) should be a directory"       )
       return
      _lowercase							      =os.path.join(
          UpperCAmelCase		,     (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']       )

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

      return (out_vocab_file,)





# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


UpperCAmelCase__   	=							{
    '''configuration_efficientnet''': [
        '''EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''EfficientNetConfig''',
        '''EfficientNetOnnxConfig''',
    ]
}

try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCAmelCase__   	=							['''EfficientNetImageProcessor''']

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCAmelCase__   	=							[
      '''EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST''',
      '''EfficientNetForImageClassification''',
      '''EfficientNetModel''',
      '''EfficientNetPreTrainedModel''',
  ]

if TYPE_CHECKING:
  from .configuration_efficientnet import (
      EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
      EfficientNetConfig,
      EfficientNetOnnxConfig,
  )

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .image_processing_efficientnet import EfficientNetImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_efficientnet import (
        EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
        EfficientNetForImageClassification,
        EfficientNetModel,
        EfficientNetPreTrainedModel,
    )

else:
  import sys

  UpperCAmelCase__   	=							_LazyModule(__name__, globals()['''__file__'''], _import_structure)

