



"""simple docstring"""







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

import sentencepiece

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


lowercase__						:							Tuple        =      logging.get_logger(__name__)

lowercase__						:							Optional[Any]        =      {
    """source_spm""": """source.spm""",
    """target_spm""": """target.spm""",
    """vocab""": """vocab.json""",
    """target_vocab_file""": """target_vocab.json""",
    """tokenizer_config_file""": """tokenizer_config.json""",
}

lowercase__						:							Optional[int]        =      {
    """source_spm""": {
        """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/source.spm"""
    },
    """target_spm""": {
        """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/target.spm"""
    },
    """vocab""": {
        """Helsinki-NLP/opus-mt-en-de""": """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/vocab.json"""
    },
    """tokenizer_config_file""": {
        """Helsinki-NLP/opus-mt-en-de""": (
            """https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/tokenizer_config.json"""
        )
    },
}

lowercase__						:							Any        =      {"""Helsinki-NLP/opus-mt-en-de""": 5_1_2}
lowercase__						:							List[str]        =      {}







class  UpperCamelCase__  (      lowercase_    ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE    							=	VOCAB_FILES_NAMES
      _SCREAMING_SNAKE_CASE    							=	PRETRAINED_VOCAB_FILES_MAP
      _SCREAMING_SNAKE_CASE    							=	PRETRAINED_INIT_CONFIGURATION
      _SCREAMING_SNAKE_CASE    							=	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      _SCREAMING_SNAKE_CASE    							=	["input_ids", "attention_mask"]
      _SCREAMING_SNAKE_CASE    							=	re.compile(""">>.+<<"""    )  # type: re.Pattern



      def __init__( self							: Dict       ,     SCREAMING_SNAKE_CASE_							: Optional[int]       ,     SCREAMING_SNAKE_CASE_							: str       ,     SCREAMING_SNAKE_CASE_							: int       ,     SCREAMING_SNAKE_CASE_							: List[str]=None       ,     SCREAMING_SNAKE_CASE_							: Union[str, Any]=None       ,     SCREAMING_SNAKE_CASE_							: Optional[Any]=None       ,     SCREAMING_SNAKE_CASE_							: int="<unk>"       ,     SCREAMING_SNAKE_CASE_							: Tuple="</s>"       ,     SCREAMING_SNAKE_CASE_							: Optional[Any]="<pad>"       ,     SCREAMING_SNAKE_CASE_							: Tuple=5_1_2       ,     SCREAMING_SNAKE_CASE_							: Optional[Dict[str, Any]] = None       ,     SCREAMING_SNAKE_CASE_							: Optional[Any]=False       ,     **SCREAMING_SNAKE_CASE_							: Optional[int]       ,     ):
        lowerCAmelCase_  :							List[Any]								=					{} if sp_model_kwargs is None else sp_model_kwargs

        super().__init__(
            # bos_token=bos_token,  unused. Start decoding with config.decoder_start_token_id
            source_lang=UpperCAmelCase__       ,     target_lang=UpperCAmelCase__       ,     unk_token=UpperCAmelCase__       ,     eos_token=UpperCAmelCase__       ,     pad_token=UpperCAmelCase__       ,     model_max_length=UpperCAmelCase__       ,     sp_model_kwargs=self.sp_model_kwargs       ,     target_vocab_file=UpperCAmelCase__       ,     separate_vocabs=UpperCAmelCase__       ,     **UpperCAmelCase__       ,     )
        assert Path(UpperCAmelCase__			).exists(), F"cannot find spm source {source_spm}"

        lowerCAmelCase_  :							Tuple								=					separate_vocabs
        lowerCAmelCase_  :							str								=					load_json(UpperCAmelCase__			)
        if self.unk_token not in self.encoder:
          raise KeyError('<unk> token must be in vocab'			)
        assert self.pad_token in self.encoder

        if separate_vocabs:
          lowerCAmelCase_  :							List[Any]								=					load_json(UpperCAmelCase__			)
          lowerCAmelCase_  :							Tuple								=					{v: k for k, v in self.target_encoder.items()}
          lowerCAmelCase_  :							List[Any]								=					[]
        else:
          lowerCAmelCase_  :							str								=					{v: k for k, v in self.encoder.items()}
          lowerCAmelCase_  :							Tuple								=					[k for k in self.encoder if k.startswith('>>'			) and k.endswith('<<'			)]

        lowerCAmelCase_  :							Union[str, Any]								=					source_lang
        lowerCAmelCase_  :							str								=					target_lang
        lowerCAmelCase_  :							Dict								=					[source_spm, target_spm]

        # load SentencePiece model for pre-processing
        lowerCAmelCase_  :							Optional[Any]								=					load_spm(UpperCAmelCase__       ,     self.sp_model_kwargs			)
        lowerCAmelCase_  :							Union[str, Any]								=					load_spm(UpperCAmelCase__       ,     self.sp_model_kwargs			)
        lowerCAmelCase_  :							List[Any]								=					self.spm_source
        lowerCAmelCase_  :							Optional[Any]								=					self.encoder

        # Multilingual target side: default to using first supported language code.

        self._setup_normalizer()



      def 	SCREAMING_SNAKE_CASE__					( self							: str			):
        try:
          from sacremoses import MosesPunctNormalizer

          lowerCAmelCase_  :							Any								=					MosesPunctNormalizer(self.source_lang			).normalize
        except (ImportError, FileNotFoundError):
          warnings.warn('Recommended: pip install sacremoses.'			)
          lowerCAmelCase_  :							Tuple								=					lambda SCREAMING_SNAKE_CASE_			: x



      def 	SCREAMING_SNAKE_CASE__					( self							: Optional[int]       ,     SCREAMING_SNAKE_CASE_							: str			):
        return self.punc_normalizer(UpperCAmelCase__			) if x else ""



      def 	SCREAMING_SNAKE_CASE__					( self							: Dict       ,     SCREAMING_SNAKE_CASE_							: Tuple			):
        return self.current_encoder.get(UpperCAmelCase__       ,     self.current_encoder[self.unk_token]			)



      def 	SCREAMING_SNAKE_CASE__					( self							: int       ,     SCREAMING_SNAKE_CASE_							: str			):
        lowerCAmelCase_  :							Any								=					self.language_code_re.match(UpperCAmelCase__			)
        lowerCAmelCase_  :							str								=					[match.group(0			)] if match else []
        return code, self.language_code_re.sub(''       ,     UpperCAmelCase__			)



      def 	SCREAMING_SNAKE_CASE__					( self							: int       ,     SCREAMING_SNAKE_CASE_							: str			):
        lowerCAmelCase_		,lowerCAmelCase_  :							Optional[Any]								=					self.remove_language_code(UpperCAmelCase__			)
        lowerCAmelCase_  :							Optional[int]								=					self.current_spm.encode(UpperCAmelCase__       ,     out_type=UpperCAmelCase__			)
        return code + pieces



      def 	SCREAMING_SNAKE_CASE__					( self							: str       ,     SCREAMING_SNAKE_CASE_							: int			):
        return self.decoder.get(UpperCAmelCase__       ,     self.unk_token			)



      def 	SCREAMING_SNAKE_CASE__					( self							: Any       ,     SCREAMING_SNAKE_CASE_							: Any       ,     **SCREAMING_SNAKE_CASE_							: List[Any]			):
        return super().batch_decode(UpperCAmelCase__       ,     **UpperCAmelCase__			)



      def 	SCREAMING_SNAKE_CASE__					( self							: Union[str, Any]       ,     SCREAMING_SNAKE_CASE_							: int       ,     **SCREAMING_SNAKE_CASE_							: List[Any]			):
        return super().decode(UpperCAmelCase__       ,     **UpperCAmelCase__			)



      def 	SCREAMING_SNAKE_CASE__					( self							: Any       ,     SCREAMING_SNAKE_CASE_							: List[str]			):
        lowerCAmelCase_  :							str								=					self.spm_source if self._decode_use_source_tokenizer else self.spm_target
        lowerCAmelCase_  :							List[Any]								=					[]
        lowerCAmelCase_  :							Tuple								=					''
        for token in tokens:
          # make sure that special tokens are not decoded using sentencepiece model
          if token in self.all_special_tokens:
            out_string += sp_model.decode_pieces(UpperCAmelCase__			) + token + " "
            lowerCAmelCase_  :							List[str]								=					[]
          else:
            current_sub_tokens.append(UpperCAmelCase__			)
        out_string += sp_model.decode_pieces(UpperCAmelCase__			)
        return out_string.strip()



      def 	SCREAMING_SNAKE_CASE__					( self							: Tuple       ,     SCREAMING_SNAKE_CASE_							: Dict       ,     SCREAMING_SNAKE_CASE_							: Optional[Any]=None			):
        if token_ids_a is None:
          return token_ids_a + [self.eos_token_id]
        # We don't expect to process pairs, but leave the pair logic for API consistency
        return token_ids_a + token_ids_a + [self.eos_token_id]



      def 	SCREAMING_SNAKE_CASE__					( self							: Union[str, Any]			):
        lowerCAmelCase_  :							List[str]								=					self.spm_source
        lowerCAmelCase_  :							int								=					self.encoder



      def 	SCREAMING_SNAKE_CASE__					( self							: List[str]			):
        lowerCAmelCase_  :							Dict								=					self.spm_target
        if self.separate_vocabs:
          lowerCAmelCase_  :							Tuple								=					self.target_encoder



      @property
      def 	SCREAMING_SNAKE_CASE__					( self							: List[str]			):
        return len(self.encoder			)



      def 	SCREAMING_SNAKE_CASE__					( self							: Dict       ,     SCREAMING_SNAKE_CASE_							: str       ,     SCREAMING_SNAKE_CASE_							: Optional[str] = None			):
        if not os.path.isdir(UpperCAmelCase__			):
          logger.error(F"Vocabulary path ({save_directory}) should be a directory"			)
          return
        lowerCAmelCase_  :							int								=					[]

        if self.separate_vocabs:
          lowerCAmelCase_  :							List[str]								=					os.path.join(
              UpperCAmelCase__       ,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab']       ,     )
          lowerCAmelCase_  :							Optional[int]								=					os.path.join(
              UpperCAmelCase__       ,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['target_vocab_file']       ,     )
          save_json(self.encoder       ,     UpperCAmelCase__			)
          save_json(self.target_encoder       ,     UpperCAmelCase__			)
          saved_files.append(UpperCAmelCase__			)
          saved_files.append(UpperCAmelCase__			)
        else:
          lowerCAmelCase_  :							Optional[int]								=					os.path.join(
              UpperCAmelCase__       ,     (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab']			)
          save_json(self.encoder       ,     UpperCAmelCase__			)
          saved_files.append(UpperCAmelCase__			)

        for spm_save_filename, spm_orig_path, spm_model in zip(
            [VOCAB_FILES_NAMES['source_spm'], VOCAB_FILES_NAMES['target_spm']]       ,     self.spm_files       ,     [self.spm_source, self.spm_target]       ,     ):
          lowerCAmelCase_  :							Dict								=					os.path.join(
              UpperCAmelCase__       ,     (filename_prefix + '-' if filename_prefix else '') + spm_save_filename			)
          if os.path.abspath(UpperCAmelCase__			) != os.path.abspath(UpperCAmelCase__			) and os.path.isfile(UpperCAmelCase__			):
            copyfile(UpperCAmelCase__       ,     UpperCAmelCase__			)
            saved_files.append(UpperCAmelCase__			)
          elif not os.path.isfile(UpperCAmelCase__			):
            with open(UpperCAmelCase__       ,     'wb'			) as fi:
              lowerCAmelCase_  :							Tuple								=					spm_model.serialized_model_proto()
              fi.write(UpperCAmelCase__			)
            saved_files.append(UpperCAmelCase__			)

        return tuple(UpperCAmelCase__			)



      def 	SCREAMING_SNAKE_CASE__					( self							: List[Any]			):
        return self.get_src_vocab()



      def 	SCREAMING_SNAKE_CASE__					( self							: List[str]			):
        return dict(self.encoder       ,     **self.added_tokens_encoder			)



      def 	SCREAMING_SNAKE_CASE__					( self							: Any			):
        return dict(self.target_encoder       ,     **self.added_tokens_decoder			)



      def __getstate__( self							: int			):
        lowerCAmelCase_  :							Optional[int]								=					self.__dict__.copy()
        state.update(
            {k: None for k in ['spm_source', 'spm_target', 'current_spm', 'punc_normalizer', 'target_vocab_file']}			)
        return state



      def __setstate__( self							: Any       ,     SCREAMING_SNAKE_CASE_							: Dict			):
        lowerCAmelCase_  :							Optional[Any]								=					d

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

        lowerCAmelCase_		,lowerCAmelCase_  :							Union[str, Any]								=					(load_spm(UpperCAmelCase__       ,     self.sp_model_kwargs			) for f in self.spm_files)
        lowerCAmelCase_  :							List[str]								=					self.spm_source
        self._setup_normalizer()



      def 	SCREAMING_SNAKE_CASE__					( self							: Optional[Any]       ,     *SCREAMING_SNAKE_CASE_							: List[str]       ,     **SCREAMING_SNAKE_CASE_							: List[Any]			):
        return 1



      def 	SCREAMING_SNAKE_CASE__					( self							: Optional[int]       ,     SCREAMING_SNAKE_CASE_							: Any			):
        lowerCAmelCase_  :							Optional[int]								=					set(self.all_special_ids			)  # call it once instead of inside list comp
        all_special_ids.remove(self.unk_token_id			)  # <unk> is only sometimes special
        return [1 if x in all_special_ids else 0 for x in seq]





      def 	SCREAMING_SNAKE_CASE__					( self							: List[str]       ,     SCREAMING_SNAKE_CASE_							: List       ,     SCREAMING_SNAKE_CASE_							: Optional[List] = None       ,     SCREAMING_SNAKE_CASE_							: bool = False			):
        if already_has_special_tokens:
          return self._special_token_mask(UpperCAmelCase__			)
        elif token_ids_a is None:
          return self._special_token_mask(UpperCAmelCase__			) + [1]
        else:
          return self._special_token_mask(token_ids_a + token_ids_a			) + [1]




def 							UpperCamelCase_       (       lowerCAmelCase__ :							str       ,  lowerCAmelCase__ :							Dict[str, Any]		)		->  sentencepiece.SentencePieceProcessor:

  """simple docstring"""




  lowerCAmelCase_  :							str								=					sentencepiece.SentencePieceProcessor(**UpperCamelCase_		)
  spm.Load(UpperCamelCase_		)
  return spm

def 							UpperCamelCase_       (       lowerCAmelCase__ :							List[str]       ,  lowerCAmelCase__ :							str		)		->  None:

  """simple docstring"""




  with open(UpperCamelCase_       ,  'w'		) as f:
    json.dump(UpperCamelCase_       ,  UpperCamelCase_       ,  indent=2		)

def 							UpperCamelCase_       (       lowerCAmelCase__ :							str		)		->  Union[Dict, List]:

  """simple docstring"""




  with open(UpperCamelCase_       ,  'r'		) as f:
    return json.load(UpperCamelCase_		)








"""simple docstring"""





def     _A    (    UpperCamelCase_	:			str)      ->		int:
   '''simple docstring'''


   __lowercase								=		0
   for plain_chr in plain_text:
      __lowercase								=		(
          ord(UpperCamelCase_) + (hash_value << 6) + (hash_value << 16) - hash_value
      )
   return hash_value




