


"""simple docstring"""

from typing import TYPE_CHECKING

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


UpperCAmelCase__					={
    "configuration_nezha": ["NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP", "NezhaConfig"],
}

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       UpperCAmelCase__					=[
           "NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST",
           "NezhaForNextSentencePrediction",
           "NezhaForMaskedLM",
           "NezhaForPreTraining",
           "NezhaForMultipleChoice",
           "NezhaForQuestionAnswering",
           "NezhaForSequenceClassification",
           "NezhaForTokenClassification",
           "NezhaModel",
           "NezhaPreTrainedModel",
       ]


if TYPE_CHECKING:
       from .configuration_nezha import NEZHA_PRETRAINED_CONFIG_ARCHIVE_MAP, NezhaConfig

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_nezha import (
                  NEZHA_PRETRAINED_MODEL_ARCHIVE_LIST,
                  NezhaForMaskedLM,
                  NezhaForMultipleChoice,
                  NezhaForNextSentencePrediction,
                  NezhaForPreTraining,
                  NezhaForQuestionAnswering,
                  NezhaForSequenceClassification,
                  NezhaForTokenClassification,
                  NezhaModel,
                  NezhaPreTrainedModel,
              )


else:
       import sys

       UpperCAmelCase__					=_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)




"""simple docstring"""

import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

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


UpperCAmelCase__					=logging.get_logger(__name__)

UpperCAmelCase__					="▁"

UpperCAmelCase__					={
    "vocab_file": "vocab.json",
    "spm_file": "sentencepiece.bpe.model",
    "tokenizer_config_file": "tokenizer_config.json",
}

UpperCAmelCase__					={
    "vocab_file": {
        "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json",
        "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json",
    },
    "spm_file": {
        "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model",
        "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model",
    },
    "tokenizer_config_file": {
        "facebook/m2m100_418M": "https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json",
        "facebook/m2m100_1.2B": "https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json",
    },
}

UpperCAmelCase__					={
    "facebook/m2m100_418M": 1024,
}

# fmt: off
UpperCAmelCase__					={
    "m2m100": ["af", "am", "ar", "ast", "az", "ba", "be", "bg", "bn", "br", "bs", "ca", "ceb", "cs", "cy", "da", "de", "el", "en", "es", "et", "fa", "ff", "fi", "fr", "fy", "ga", "gd", "gl", "gu", "ha", "he", "hi", "hr", "ht", "hu", "hy", "id", "ig", "ilo", "is", "it", "ja", "jv", "ka", "kk", "km", "kn", "ko", "lb", "lg", "ln", "lo", "lt", "lv", "mg", "mk", "ml", "mn", "mr", "ms", "my", "ne", "nl", "no", "ns", "oc", "or", "pa", "pl", "ps", "pt", "ro", "ru", "sd", "si", "sk", "sl", "so", "sq", "sr", "ss", "su", "sv", "sw", "ta", "th", "tl", "tn", "tr", "uk", "ur", "uz", "vi", "wo", "xh", "yi", "yo", "zh", "zu"],
    "wmt21": ["en", "ha", "is", "ja", "cs", "ru", "zh", "de"]
}





class  lowerCamelCase__    (		_a     ):
      a			:  str           =		VOCAB_FILES_NAMES
      a			:  Dict           =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      a			:  int           =		PRETRAINED_VOCAB_FILES_MAP
      a			:  Union[str, Any]           =		["""input_ids""", """attention_mask"""]

      a			:  List[int]           =		[]
      a			:  List[int]           =		[]
      def __init__(		self						:						Optional[Any]   ,							A_						:						str   ,							A_						:						Dict   ,							A_						:						str=None   ,							A_						:						Dict=None   ,							A_						:						str="<s>"   ,							A_						:						Any="</s>"   ,							A_						:						List[Any]="</s>"   ,							A_						:						List[str]="<pad>"   ,							A_						:						Optional[int]="<unk>"   ,							A_						:						str="m2m100"   ,							A_						:						Optional[Dict[str, Any]] = None   ,							A_						:						Tuple=8   ,							**A_						:						Dict   ,							):






       '''simple docstring'''


       __lowercase						=						{} if sp_model_kwargs is None else sp_model_kwargs

       __lowercase						=						language_codes
       __lowercase						=						FAIRSEQ_LANGUAGE_CODES[language_codes]
       __lowercase						=						{lang_code: F'''__{lang_code}__''' for lang_code in fairseq_language_code}

       __lowercase						=						kwargs.get("""additional_special_tokens"""   ,							[]				)
       kwargs["additional_special_tokens"] += [
           self.get_lang_token(A_				)
           for lang_code in fairseq_language_code
           if self.get_lang_token(A_				) not in kwargs["additional_special_tokens"]
       ]

       super().__init__(
           src_lang=A_   ,							tgt_lang=A_   ,							bos_token=A_   ,							eos_token=A_   ,							sep_token=A_   ,							unk_token=A_   ,							pad_token=A_   ,							language_codes=A_   ,							sp_model_kwargs=self.sp_model_kwargs   ,							num_madeup_words=A_   ,							**A_   ,							)

       __lowercase						=						vocab_file
       __lowercase						=						load_json(A_				)
       __lowercase						=						{v: k for k, v in self.encoder.items()}
       __lowercase						=						spm_file
       __lowercase						=						load_spm(A_   ,							self.sp_model_kwargs				)

       __lowercase						=						len(self.encoder				)

       __lowercase						=						{
           self.get_lang_token(A_				): self.encoder_size + i for i, lang_code in enumerate(A_				)
       }
       __lowercase						=						{lang_code: self.encoder_size + i for i, lang_code in enumerate(A_				)}
       __lowercase						=						{v: k for k, v in self.lang_token_to_id.items()}

       __lowercase						=						src_lang if src_lang is not None else """en"""
       __lowercase						=						tgt_lang
       __lowercase						=						self.get_lang_id(self._src_lang				)
       self.set_src_lang_special_tokens(self._src_lang				)

       __lowercase						=						num_madeup_words
      @property
      def SCREAMING_SNAKE_CASE_						(		self						:						Union[str, Any]				):






       '''simple docstring'''


       return len(self.encoder				) + len(self.lang_token_to_id				)
      @property
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict				):






       '''simple docstring'''


       return self._src_lang
      @src_lang.setter
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						new_src_lang
       self.set_src_lang_special_tokens(self._src_lang				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       return self.sp_model.encode(A_   ,							out_type=A_				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[Any]   ,							A_						:						str				):






       '''simple docstring'''


       if token in self.lang_token_to_id:
        return self.lang_token_to_id[token]
       return self.encoder.get(A_   ,							self.encoder[self.unk_token]				)
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]   ,							A_						:						int				):






       '''simple docstring'''


       if index in self.id_to_lang_token:
        return self.id_to_lang_token[index]
       return self.decoder.get(A_   ,							self.unk_token				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Tuple   ,							A_						:						Union[str, Any]				):






       '''simple docstring'''


       __lowercase						=						[]
       __lowercase						=						""""""
       for token in tokens:
        # make sure that special tokens are not decoded using sentencepiece model
        if token in self.all_special_tokens:
         out_string += self.sp_model.decode(A_				) + token
         __lowercase						=						[]
        else:
         current_sub_tokens.append(A_				)
       out_string += self.sp_model.decode(A_				)
       return out_string.strip()
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]   ,							A_						:						List[int]   ,							A_						:						Optional[List[int]] = None   ,							A_						:						bool = False				):






       '''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_				)

       __lowercase						=						[1] * len(self.prefix_tokens				)
       __lowercase						=						[1] * len(self.suffix_tokens				)
       if token_ids_a is None:
        return prefix_ones + ([0] * len(A_				)) + suffix_ones
       return prefix_ones + ([0] * len(A_				)) + ([0] * len(A_				)) + suffix_ones
      def SCREAMING_SNAKE_CASE_						(		self						:						Any   ,							A_						:						List[int]   ,							A_						:						Optional[List[int]] = None				):






       '''simple docstring'''


       if token_ids_a is None:
        return self.prefix_tokens + token_ids_a + self.suffix_tokens
       # We don't expect to process pairs, but leave the pair logic for API consistency
       return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]				):






       '''simple docstring'''


       __lowercase						=						{self.convert_ids_to_tokens(A_				): i for i in range(self.vocab_size				)}
       vocab.update(self.added_tokens_encoder				)
       return vocab
      def __getstate__(		self						:						List[str]				):






       '''simple docstring'''


       __lowercase						=						self.__dict__.copy()
       __lowercase						=						None
       return state
      def __setstate__(		self						:						Optional[Any]   ,							A_						:						Dict				):






       '''simple docstring'''


       __lowercase						=						d

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

       __lowercase						=						load_spm(self.spm_file   ,							self.sp_model_kwargs				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Tuple   ,							A_						:						str   ,							A_						:						Optional[str] = None				):






       '''simple docstring'''


       __lowercase						=						Path(A_				)
       if not save_dir.is_dir():
        raise OSError(F'''{save_directory} should be a directory'''				)
       __lowercase						=						save_dir / (
           (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""vocab_file"""]
       )
       __lowercase						=						save_dir / (
           (filename_prefix + """-""" if filename_prefix else """""") + self.vocab_files_names["""spm_file"""]
       )

       save_json(self.encoder   ,							A_				)

       if os.path.abspath(self.spm_file				) != os.path.abspath(A_				) and os.path.isfile(self.spm_file				):
        copyfile(self.spm_file   ,							A_				)
       elif not os.path.isfile(self.spm_file				):
        with open(A_   ,							"""wb"""				) as fi:
         __lowercase						=						self.sp_model.serialized_model_proto()
         fi.write(A_				)

       return (str(A_				), str(A_				))
      def SCREAMING_SNAKE_CASE_						(		self						:						List[Any]   ,							A_						:						List[str]   ,							A_						:						str = "en"   ,							A_						:						Optional[List[str]] = None   ,							A_						:						str = "ro"   ,							**A_						:						List[Any]   ,							):






       '''simple docstring'''


       __lowercase						=						src_lang
       __lowercase						=						tgt_lang
       self.set_src_lang_special_tokens(self.src_lang				)
       return super().prepare_seqaseq_batch(A_   ,							A_   ,							**A_				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[int]   ,							A_						:						List[Any]   ,							A_						:						Optional[str]   ,							A_						:						Optional[str]   ,							**A_						:						Optional[Any]				):






       '''simple docstring'''


       if src_lang is None or tgt_lang is None:
        raise ValueError("""Translation requires a `src_lang` and a `tgt_lang` for this model"""				)
       __lowercase						=						src_lang
       __lowercase						=						self(A_   ,							add_special_tokens=A_   ,							**A_				)
       __lowercase						=						self.get_lang_id(A_				)
       __lowercase						=						tgt_lang_id
       return inputs
      def SCREAMING_SNAKE_CASE_						(		self						:						List[str]				):






       '''simple docstring'''


       self.set_src_lang_special_tokens(self.src_lang				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[int]				):






       '''simple docstring'''


       self.set_tgt_lang_special_tokens(self.tgt_lang				)
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[Any]   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						self.get_lang_token(A_				)
       __lowercase						=						self.lang_token_to_id[lang_token]
       __lowercase						=						[self.cur_lang_id]
       __lowercase						=						[self.eos_token_id]
      def SCREAMING_SNAKE_CASE_						(		self						:						Optional[int]   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						self.get_lang_token(A_				)
       __lowercase						=						self.lang_token_to_id[lang_token]
       __lowercase						=						[self.cur_lang_id]
       __lowercase						=						[self.eos_token_id]
      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       return self.lang_code_to_token[lang]






      def SCREAMING_SNAKE_CASE_						(		self						:						Dict   ,							A_						:						str				):






       '''simple docstring'''


       __lowercase						=						self.get_lang_token(A_				)
       return self.lang_token_to_id[lang_token]






def lowerCAmelCase_   (					UpperCamelCase__						:			str					, UpperCamelCase__						:			Dict[str, Any]			):






 """simple docstring"""







 __lowercase						=						sentencepiece.SentencePieceProcessor(**UpperCamelCase__			)
 spm.Load(str(UpperCamelCase__			)			)
 return spm


def lowerCAmelCase_   (					UpperCamelCase__						:			str			):






 """simple docstring"""







 with open(UpperCamelCase__					, """r"""			) as f:
  return json.load(UpperCamelCase__			)


def lowerCAmelCase_   (					UpperCamelCase__						:			List[str]					, UpperCamelCase__						:			str			):






 """simple docstring"""







 with open(UpperCamelCase__					, """w"""			) as f:
  json.dump(UpperCamelCase__					, UpperCamelCase__					, indent=2			)
