


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


UpperCAmelCase_	:     Any							     =	logging.get_logger(__name__)

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

UpperCAmelCase_	:     Any							     =	{
    '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'
        )
    },
}

UpperCAmelCase_	:     List[str]							     =	{'Helsinki-NLP/opus-mt-en-de': 512}
UpperCAmelCase_	:     Union[str, Any]							     =	{}





class 					lowercase__						(		_snake_case      ):





							'''simple docstring'''


							A_							:   str   			=						VOCAB_FILES_NAMES
							A_							:   Tuple   			=						PRETRAINED_VOCAB_FILES_MAP
							A_							:   Any   			=						PRETRAINED_INIT_CONFIGURATION
							A_							:   int   			=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							A_							:   List[str]   			=						["""input_ids""", """attention_mask"""]
							A_							:   Tuple   			=						re.compile(""">>.+<<"""      )  # type: re.Pattern






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

											_SCREAMING_SNAKE_CASE				: Optional[Any]  	=   separate_vocabs
											_SCREAMING_SNAKE_CASE				: Optional[int]  	=   load_json(__snake_case						)
											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				: Union[str, Any]  	=   load_json(__snake_case						)
															_SCREAMING_SNAKE_CASE				: Dict  	=   {v: k for k, v in self.target_encoder.items()}
															_SCREAMING_SNAKE_CASE				: List[str]  	=   []
											else:
															_SCREAMING_SNAKE_CASE				: int  	=   {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				: Optional[int]  	=   source_lang
											_SCREAMING_SNAKE_CASE				: Any  	=   target_lang
											_SCREAMING_SNAKE_CASE				: Tuple  	=   [source_spm, target_spm]

											# load SentencePiece model for pre-processing
											_SCREAMING_SNAKE_CASE				: str  	=   load_spm(__snake_case					,      self.sp_model_kwargs						)
											_SCREAMING_SNAKE_CASE				: Tuple  	=   load_spm(__snake_case					,      self.sp_model_kwargs						)
											_SCREAMING_SNAKE_CASE				: Union[str, Any]  	=   self.spm_source
											_SCREAMING_SNAKE_CASE				: Tuple  	=   self.encoder

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

											self._setup_normalizer()






							def UpperCAmelCase_			(					self						):
											try:
															from sacremoses import MosesPunctNormalizer

															_SCREAMING_SNAKE_CASE				: Union[str, Any]  	=   MosesPunctNormalizer(self.source_lang						).normalize
											except (ImportError, FileNotFoundError):
															warnings.warn("""Recommended: pip install sacremoses."""						)
															_SCREAMING_SNAKE_CASE				: List[str]  	=   lambda __snake_case						: x






							def UpperCAmelCase_			(					self					,      __snake_case						):
											return self.punc_normalizer(__snake_case						) if x else ""






							def UpperCAmelCase_			(					self					,      __snake_case						):
											return self.current_encoder.get(__snake_case					,      self.current_encoder[self.unk_token]						)






							def UpperCAmelCase_			(					self					,      __snake_case						):
											_SCREAMING_SNAKE_CASE				: Tuple  	=   self.language_code_re.match(__snake_case						)
											_SCREAMING_SNAKE_CASE				: list  	=   [match.group(0						)] if match else []
											return code, self.language_code_re.sub(""""""					,      __snake_case						)






							def UpperCAmelCase_			(					self					,      __snake_case						):
											_SCREAMING_SNAKE_CASE				: List[str]  	=   self.remove_language_code(__snake_case						)
											_SCREAMING_SNAKE_CASE				: Any  	=   self.current_spm.encode(__snake_case					,      out_type=__snake_case						)
											return code + pieces






							def UpperCAmelCase_			(					self					,      __snake_case						):
											return self.decoder.get(__snake_case					,      self.unk_token						)






							def UpperCAmelCase_			(					self					,      __snake_case					,      **__snake_case						):
											return super().batch_decode(__snake_case					,      **__snake_case						)






							def UpperCAmelCase_			(					self					,      __snake_case					,      **__snake_case						):
											return super().decode(__snake_case					,      **__snake_case						)






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






							def UpperCAmelCase_			(					self					,      __snake_case					,      __snake_case=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 UpperCAmelCase_			(					self						):
											_SCREAMING_SNAKE_CASE				: List[Any]  	=   self.spm_source
											_SCREAMING_SNAKE_CASE				: Optional[int]  	=   self.encoder






							def UpperCAmelCase_			(					self						):
											_SCREAMING_SNAKE_CASE				: Dict  	=   self.spm_target
											if self.separate_vocabs:
															_SCREAMING_SNAKE_CASE				: str  	=   self.target_encoder






							@property
							def UpperCAmelCase_			(					self						):
											return len(self.encoder						)






							def UpperCAmelCase_			(					self					,      __snake_case					,      __snake_case = None						):
											if not os.path.isdir(__snake_case						):
															logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""						)
															return
											_SCREAMING_SNAKE_CASE				: Any  	=   []

											if self.separate_vocabs:
															_SCREAMING_SNAKE_CASE				: int  	=   os.path.join(
															    __snake_case					,      (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab"""]					,      )
															_SCREAMING_SNAKE_CASE				: List[Any]  	=   os.path.join(
															    __snake_case					,      (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""target_vocab_file"""]					,      )
															save_json(self.encoder					,      __snake_case						)
															save_json(self.target_encoder					,      __snake_case						)
															saved_files.append(__snake_case						)
															saved_files.append(__snake_case						)
											else:
															_SCREAMING_SNAKE_CASE				: List[Any]  	=   os.path.join(
															    __snake_case					,      (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab"""]						)
															save_json(self.encoder					,      __snake_case						)
															saved_files.append(__snake_case						)

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

											return tuple(__snake_case						)






							def UpperCAmelCase_			(					self						):
											return self.get_src_vocab()






							def UpperCAmelCase_			(					self						):
											return dict(self.encoder					,      **self.added_tokens_encoder						)






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






							def __getstate__(					self						):
											_SCREAMING_SNAKE_CASE				: Union[str, Any]  	=   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					,      __snake_case						):
											_SCREAMING_SNAKE_CASE				: List[str]  	=   d

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

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






							def UpperCAmelCase_			(					self					,      *__snake_case					,      **__snake_case						):
											return 1






							def UpperCAmelCase_			(					self					,      __snake_case						):
											_SCREAMING_SNAKE_CASE				: Tuple  	=   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 UpperCAmelCase_			(					self					,      __snake_case					,      __snake_case = None					,      __snake_case = False						):
											if already_has_special_tokens:
															return self._special_token_mask(__snake_case						)
											elif token_ids_a is None:
															return self._special_token_mask(__snake_case						) + [1]
											else:
															return self._special_token_mask(token_ids_a + token_ids_a						) + [1]







def     snake_case_     (						SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__  ):







				"""simple docstring"""





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







def     snake_case_     (						SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__  ):







				"""simple docstring"""





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







def     snake_case_     (						SCREAMING_SNAKE_CASE__  ):







				"""simple docstring"""





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








'''simple docstring'''


def     snake_case_     (						SCREAMING_SNAKE_CASE__							,   SCREAMING_SNAKE_CASE__  ):







				"""simple docstring"""





				return (input_a, input_a).count(0  ) % 2







def     snake_case_     (						):







				"""simple docstring"""





				assert xor_gate(0							,   0  ) == 0
				assert xor_gate(0							,   1  ) == 1
				assert xor_gate(1							,   0  ) == 1
				assert xor_gate(1							,   1  ) == 0


if __name__ == "__main__":
				print(xor_gate(0, 0))
				print(xor_gate(0, 1))




