

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


a__		:   List[Any]            =       logging.get_logger(__name__)

a__		:   List[str]            =       {
    """source_spm""": """source.spm""",
    """target_spm""": """target.spm""",
    """vocab""": """vocab.json""",
    """target_vocab_file""": """target_vocab.json""",
    """tokenizer_config_file""": """tokenizer_config.json""",
}

a__		:   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"""
        )
    },
}

a__		:   Optional[int]            =       {"""Helsinki-NLP/opus-mt-en-de""": 5_1_2}
a__		:   Any            =       {}


class  UpperCamelCase__  (    a__):
 UpperCAmelCase__    :    Optional[int]										=					VOCAB_FILES_NAMES
 UpperCAmelCase__    :    int										=					PRETRAINED_VOCAB_FILES_MAP
 UpperCAmelCase__    :    Tuple										=					PRETRAINED_INIT_CONFIGURATION
 UpperCAmelCase__    :    List[str]										=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 UpperCAmelCase__    :    int										=					['input_ids', 'attention_mask']
 UpperCAmelCase__    :    str										=					re.compile('>>.+<<')  # type: re.Pattern






 def __init__(			self  :Optional[int]	,				_A  :Optional[Any]	,				_A  :Optional[int]	,				_A  :int	,				_A  :Union[str, Any]=None	,				_A  :Optional[int]=None	,				_A  :Optional[int]=None	,				_A  :str="<unk>"	,				_A  :int="</s>"	,				_A  :List[Any]="<pad>"	,				_A  :Dict=512	,				_A  :Tuple = None	,				_A  :Tuple=False	,				**_A  :int	,				)				->			None:







       '''simple docstring'''



       __A       	=			{} 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}'

       __A       	=			separate_vocabs
       __A       	=			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:
             __A       	=			load_json(__A			)
             __A       	=			{v: k for k, v in self.target_encoder.items()}
             __A       	=			[]
       else:
             __A       	=			{v: k for k, v in self.encoder.items()}
             __A       	=			[k for k in self.encoder if k.startswith('>>'			) and k.endswith('<<'			)]

       __A       	=			source_lang
       __A       	=			target_lang
       __A       	=			[source_spm, target_spm]

       # load SentencePiece model for pre-processing
       __A       	=			load_spm(__A	,				self.sp_model_kwargs			)
       __A       	=			load_spm(__A	,				self.sp_model_kwargs			)
       __A       	=			self.spm_source
       __A       	=			self.encoder

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

       self._setup_normalizer()






 def 	lowercase_						(			self  :Dict			)				->			Any:







       '''simple docstring'''



       try:
             from sacremoses import MosesPunctNormalizer

             __A       	=			MosesPunctNormalizer(self.source_lang			).normalize
       except (ImportError, FileNotFoundError):
             warnings.warn('Recommended: pip install sacremoses.'			)
             __A       	=			lambda _A			: x






 def 	lowercase_						(			self  :Optional[Any]	,				_A  :Optional[int]			)				->			str:







       '''simple docstring'''



       return self.punc_normalizer(__A			) if x else ""






 def 	lowercase_						(			self  :Optional[int]	,				_A  :str			)				->			Union[str, Any]:







       '''simple docstring'''



       return self.current_encoder.get(__A	,				self.current_encoder[self.unk_token]			)






 def 	lowercase_						(			self  :int	,				_A  :List[Any]			)				->			Union[str, Any]:







       '''simple docstring'''



       __A       	=			self.language_code_re.match(__A			)
       __A       	=			[match.group(0			)] if match else []
       return code, self.language_code_re.sub(''	,				__A			)






 def 	lowercase_						(			self  :int	,				_A  :str			)				->			List[str]:







       '''simple docstring'''



       __A       	=			self.remove_language_code(__A			)
       __A       	=			self.current_spm.encode(__A	,				out_type=__A			)
       return code + pieces






 def 	lowercase_						(			self  :str	,				_A  :List[str]			)				->			str:







       '''simple docstring'''



       return self.decoder.get(__A	,				self.unk_token			)






 def 	lowercase_						(			self  :List[Any]	,				_A  :Optional[int]	,				**_A  :int			)				->			List[str]:







       '''simple docstring'''



       return super().batch_decode(__A	,				**__A			)






 def 	lowercase_						(			self  :Any	,				_A  :Any	,				**_A  :Tuple			)				->			Tuple:







       '''simple docstring'''



       return super().decode(__A	,				**__A			)






 def 	lowercase_						(			self  :List[str]	,				_A  :List[str]			)				->			str:







       '''simple docstring'''



       __A       	=			self.spm_source if self._decode_use_source_tokenizer else self.spm_target
       __A       	=			[]
       __A       	=			""
       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 + " "
                   __A       	=			[]
             else:
                   current_sub_tokens.append(__A			)
       out_string += sp_model.decode_pieces(__A			)
       return out_string.strip()






 def 	lowercase_						(			self  :Any	,				_A  :int	,				_A  :Tuple=None			)				->			List[int]:







       '''simple docstring'''



       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 	lowercase_						(			self  :List[Any]			)				->			Union[str, Any]:







       '''simple docstring'''



       __A       	=			self.spm_source
       __A       	=			self.encoder






 def 	lowercase_						(			self  :int			)				->			Dict:







       '''simple docstring'''



       __A       	=			self.spm_target
       if self.separate_vocabs:
             __A       	=			self.target_encoder






 @property
 def 	lowercase_						(			self  :List[Any]			)				->			int:







       '''simple docstring'''



       return len(self.encoder			)






 def 	lowercase_						(			self  :Tuple	,				_A  :List[Any]	,				_A  :Any = None			)				->			Tuple[str]:







       '''simple docstring'''



       if not os.path.isdir(__A			):
             logger.error(F'Vocabulary path ({save_directory}) should be a directory'			)
             return
       __A       	=			[]

       if self.separate_vocabs:
             __A       	=			os.path.join(
                 __A	,				(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab']	,				)
             __A       	=			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:
             __A       	=			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]	,				):
             __A       	=			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:
                         __A       	=			spm_model.serialized_model_proto()
                         fi.write(__A			)
                   saved_files.append(__A			)

       return tuple(__A			)






 def 	lowercase_						(			self  :Union[str, Any]			)				->			Dict:







       '''simple docstring'''



       return self.get_src_vocab()






 def 	lowercase_						(			self  :List[Any]			)				->			Dict:







       '''simple docstring'''



       return dict(self.encoder	,				**self.added_tokens_encoder			)






 def 	lowercase_						(			self  :Union[str, Any]			)				->			List[Any]:







       '''simple docstring'''



       return dict(self.target_encoder	,				**self.added_tokens_decoder			)






 def __getstate__(			self  :Dict			)				->			Dict:







       '''simple docstring'''



       __A       	=			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  :Union[str, Any]	,				_A  :str			)				->			None:







       '''simple docstring'''



       __A       	=			d

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

       __A       	=			(load_spm(__A	,				self.sp_model_kwargs			) for f in self.spm_files)
       __A       	=			self.spm_source
       self._setup_normalizer()






 def 	lowercase_						(			self  :str	,				*_A  :Union[str, Any]	,				**_A  :Union[str, Any]			)				->			Union[str, Any]:







       '''simple docstring'''



       return 1






 def 	lowercase_						(			self  :Dict	,				_A  :Any			)				->			List[str]:







       '''simple docstring'''



       __A       	=			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 	lowercase_						(			self  :int	,				_A  :Any	,				_A  :int = None	,				_A  :List[Any] = False			)				->			List[int]:







       '''simple docstring'''



       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        snake_case							(		UpperCAmelCase      ,  UpperCAmelCase	)->			sentencepiece.SentencePieceProcessor:







      """simple docstring"""
      __A       	=			sentencepiece.SentencePieceProcessor(**UpperCAmelCase	)
      spm.Load(UpperCAmelCase	)
      return spm





def        snake_case							(		UpperCAmelCase      ,  UpperCAmelCase	)->			None:







      """simple docstring"""

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





def        snake_case							(		UpperCAmelCase	)->			Union[Dict, List]:







      """simple docstring"""

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








'''simple docstring'''





def        snake_case							(		UpperCAmelCase	)->			int:







      """simple docstring"""
      return 1 if input_a == 0 else 0





def        snake_case							(		)->			None:







      """simple docstring"""
      assert not_gate(0	) == 1
      assert not_gate(1	) == 0


if __name__ == "__main__":
 print(not_gate(0))
 print(not_gate(1))






