




'''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__								=						logging.get_logger(__name__)

lowercase__								=						{
    '''source_spm''': '''source.spm''',
    '''target_spm''': '''target.spm''',
    '''vocab''': '''vocab.json''',
    '''target_vocab_file''': '''target_vocab.json''',
    '''tokenizer_config_file''': '''tokenizer_config.json''',
}

lowercase__								=						{
    '''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__								=						{'''Helsinki-NLP/opus-mt-en-de''': 5_1_2}
lowercase__								=						{}






class     lowercase  ( UpperCamelCase_):
      __lowercase					=	VOCAB_FILES_NAMES
      __lowercase					=	PRETRAINED_VOCAB_FILES_MAP
      __lowercase					=	PRETRAINED_INIT_CONFIGURATION
      __lowercase					=	PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      __lowercase					=	['''input_ids''', '''attention_mask''']
      __lowercase					=	re.compile('''>>.+<<''')  # type: re.Pattern






      def __init__(self			,	a__			,	a__			,	a__			,	a__=None			,	a__=None			,	a__=None			,	a__="<unk>"			,	a__="</s>"			,	a__="<pad>"			,	a__=5_1_2			,	a__ = None			,	a__=False			,	**a__			,	)							-> None:
         SCREAMING_SNAKE_CASE__      :					str							    =			{} 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=__a			,	target_lang=__a			,	unk_token=__a			,	eos_token=__a			,	pad_token=__a			,	model_max_length=__a			,	sp_model_kwargs=self.sp_model_kwargs			,	target_vocab_file=__a			,	separate_vocabs=__a			,	**__a			,	)
         assert Path(__a       ).exists(), f"""cannot find spm source {source_spm}"""

         SCREAMING_SNAKE_CASE__      :					Any							    =			separate_vocabs
         SCREAMING_SNAKE_CASE__      :					Optional[int]							    =			load_json(__a       )
         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:
            SCREAMING_SNAKE_CASE__      :					int							    =			load_json(__a       )
            SCREAMING_SNAKE_CASE__      :					str							    =			{v: k for k, v in self.target_encoder.items()}
            SCREAMING_SNAKE_CASE__      :					int							    =			[]
         else:
            SCREAMING_SNAKE_CASE__      :					List[Any]							    =			{v: k for k, v in self.encoder.items()}
            SCREAMING_SNAKE_CASE__      :					list							    =			[k for k in self.encoder if k.startswith('''>>'''       ) and k.endswith('''<<'''       )]

         SCREAMING_SNAKE_CASE__      :					List[Any]							    =			source_lang
         SCREAMING_SNAKE_CASE__      :					Tuple							    =			target_lang
         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			[source_spm, target_spm]

         # load SentencePiece model for pre-processing
         SCREAMING_SNAKE_CASE__      :					int							    =			load_spm(__a			,	self.sp_model_kwargs       )
         SCREAMING_SNAKE_CASE__      :					Dict							    =			load_spm(__a			,	self.sp_model_kwargs       )
         SCREAMING_SNAKE_CASE__      :					Dict							    =			self.spm_source
         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			self.encoder

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

         self._setup_normalizer()






      def  A__(self       )							-> str:






         try:
            from sacremoses import MosesPunctNormalizer

            SCREAMING_SNAKE_CASE__      :					str							    =			MosesPunctNormalizer(self.source_lang       ).normalize
         except (ImportError, FileNotFoundError):
            warnings.warn('''Recommended: pip install sacremoses.'''       )
            SCREAMING_SNAKE_CASE__      :					Any							    =			lambda a__       : x






      def  A__(self			,	a__       )							-> str:
         return self.punc_normalizer(__a       ) if x else ""






      def  A__(self			,	a__       )							-> int:
         return self.current_encoder.get(__a			,	self.current_encoder[self.unk_token]       )






      def  A__(self			,	a__       )							-> Union[str, Any]:
         SCREAMING_SNAKE_CASE__      :					Tuple							    =			self.language_code_re.match(__a       )
         SCREAMING_SNAKE_CASE__      :					list							    =			[match.group(0       )] if match else []
         return code, self.language_code_re.sub(''''''			,	__a       )






      def  A__(self			,	a__       )							-> List[str]:
         SCREAMING_SNAKE_CASE__      :					List[Any]							    =			self.remove_language_code(__a       )
         SCREAMING_SNAKE_CASE__      :					Union[str, Any]							    =			self.current_spm.encode(__a			,	out_type=__a       )
         return code + pieces






      def  A__(self			,	a__       )							-> str:
         return self.decoder.get(__a			,	self.unk_token       )






      def  A__(self			,	a__			,	**a__       )							-> Optional[Any]:
         return super().batch_decode(__a			,	**__a       )






      def  A__(self			,	a__			,	**a__       )							-> Dict:
         return super().decode(__a			,	**__a       )






      def  A__(self			,	a__       )							-> str:
         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			self.spm_source if self._decode_use_source_tokenizer else self.spm_target
         SCREAMING_SNAKE_CASE__      :					int							    =			[]
         SCREAMING_SNAKE_CASE__      :					List[str]							    =			''
         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(__a       ) + token + " "
               SCREAMING_SNAKE_CASE__      :					List[str]							    =			[]
            else:
               current_sub_tokens.append(__a       )
         out_string += sp_model.decode_pieces(__a       )
         return out_string.strip()






      def  A__(self			,	a__			,	a__=None       )							-> List[int]:






         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  A__(self       )							-> int:
         SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			self.spm_source
         SCREAMING_SNAKE_CASE__      :					str							    =			self.encoder






      def  A__(self       )							-> Optional[Any]:
         SCREAMING_SNAKE_CASE__      :					List[Any]							    =			self.spm_target
         if self.separate_vocabs:
            SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			self.target_encoder






      @property
      def  A__(self       )							-> int:
         return len(self.encoder       )






      def  A__(self			,	a__			,	a__ = None       )							-> Tuple[str]:






         if not os.path.isdir(__a       ):
            logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""       )
            return
         SCREAMING_SNAKE_CASE__      :					List[Any]							    =			[]

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

         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]			,	):
            SCREAMING_SNAKE_CASE__      :					str							    =			os.path.join(
                __a			,	(filename_prefix + '''-''' if filename_prefix else '''''') + spm_save_filename       )
            if os.path.abspath(__a       ) != os.path.abspath(__a       ) and os.path.isfile(__a       ):
               copyfile(__a			,	__a       )
               saved_files.append(__a       )
            elif not os.path.isfile(__a       ):
               with open(__a			,	'''wb'''       ) as fi:
                  SCREAMING_SNAKE_CASE__      :					Optional[Any]							    =			spm_model.serialized_model_proto()
                  fi.write(__a       )
               saved_files.append(__a       )

         return tuple(__a       )






      def  A__(self       )							-> Dict:
         return self.get_src_vocab()






      def  A__(self       )							-> Union[str, Any]:
         return dict(self.encoder			,	**self.added_tokens_encoder       )






      def  A__(self       )							-> int:
         return dict(self.target_encoder			,	**self.added_tokens_decoder       )






      def __getstate__(self       )							-> Dict:
         SCREAMING_SNAKE_CASE__      :					Dict							    =			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			,	a__       )							-> None:
         SCREAMING_SNAKE_CASE__      :					Tuple							    =			d

         # for backward compatibility
         if not hasattr(self			,	'''sp_model_kwargs'''       ):
            SCREAMING_SNAKE_CASE__      :					List[Any]							    =			{}

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






      def  A__(self			,	*a__			,	**a__       )							-> Optional[int]:
         return 1






      def  A__(self			,	a__       )							-> Any:
         SCREAMING_SNAKE_CASE__      :					Dict							    =			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  A__(self			,	a__			,	a__ = None			,	a__ = False       )							-> List[int]:






         if already_has_special_tokens:
            return self._special_token_mask(__a       )
         elif token_ids_a is None:
            return self._special_token_mask(__a       ) + [1]
         else:
            return self._special_token_mask(token_ids_a + token_ids_a       ) + [1]


def 					UpperCamelCase						(	snake_case						,  snake_case ):




   '''simple docstring'''

   SCREAMING_SNAKE_CASE__      :					int							    =			sentencepiece.SentencePieceProcessor(**snake_case )
   spm.Load(snake_case )
   return spm


def 					UpperCamelCase						(	snake_case						,  snake_case ):




   '''simple docstring'''

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







def 					UpperCamelCase						(	snake_case ):




   '''simple docstring'''

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









'''simple docstring'''






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__A     						= {
    '''configuration_prophetnet''': ['''PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''ProphetNetConfig'''],
    '''tokenization_prophetnet''': ['''ProphetNetTokenizer'''],
}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      __A     						= [
          '''PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST''',
          '''ProphetNetDecoder''',
          '''ProphetNetEncoder''',
          '''ProphetNetForCausalLM''',
          '''ProphetNetForConditionalGeneration''',
          '''ProphetNetModel''',
          '''ProphetNetPreTrainedModel''',
      ]


if TYPE_CHECKING:
      from .configuration_prophetnet import PROPHETNET_PRETRAINED_CONFIG_ARCHIVE_MAP, ProphetNetConfig
      from .tokenization_prophetnet import ProphetNetTokenizer

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_prophetnet import (
                PROPHETNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                ProphetNetDecoder,
                ProphetNetEncoder,
                ProphetNetForCausalLM,
                ProphetNetForConditionalGeneration,
                ProphetNetModel,
                ProphetNetPreTrainedModel,
            )

else:
      import sys

      __A     						= _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)