




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

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

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





class __magic_name__(						__lowerCAmelCase      ):
						UpperCAmelCase_		:					Union[str, Any]    =  VOCAB_FILES_NAMES
						UpperCAmelCase_		:					Tuple    =  PRETRAINED_VOCAB_FILES_MAP
						UpperCAmelCase_		:					Optional[int]    =  PRETRAINED_INIT_CONFIGURATION
						UpperCAmelCase_		:					str    =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
						UpperCAmelCase_		:					Dict    =  ["""input_ids""", """attention_mask"""]
						UpperCAmelCase_		:					str    =  re.compile(""">>.+<<"""      )  # type: re.Pattern






						def __init__(   self						:						List[str]					,   __UpperCamelCase						:						List[Any]					,   __UpperCamelCase						:						Optional[int]					,   __UpperCamelCase						:						Any					,   __UpperCamelCase						:						List[Any]=None					,   __UpperCamelCase						:						Dict=None					,   __UpperCamelCase						:						List[str]=None					,   __UpperCamelCase						:						Union[str, Any]="<unk>"					,   __UpperCamelCase						:						Any="</s>"					,   __UpperCamelCase						:						Union[str, Any]="<pad>"					,   __UpperCamelCase						:						Any=5_1_2					,   __UpperCamelCase						:						Optional[Dict[str, Any]] = None					,   __UpperCamelCase						:						Optional[int]=False					,   **__UpperCamelCase						:						Dict					,   ):



									'''simple docstring'''






									snake_case__          =						{} 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}"""

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

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

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

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

									self._setup_normalizer()






						def       __lowerCAmelCase(   self						:						Tuple       ):



									'''simple docstring'''






									try:
												from sacremoses import MosesPunctNormalizer

												snake_case__          =						MosesPunctNormalizer(self.source_lang       ).normalize
									except (ImportError, FileNotFoundError):
												warnings.warn("""Recommended: pip install sacremoses."""       )
												snake_case__          =						lambda __UpperCamelCase       : x






						def       __lowerCAmelCase(   self						:						Dict					,   __UpperCamelCase						:						str       ):



									'''simple docstring'''






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






						def       __lowerCAmelCase(   self						:						List[str]					,   __UpperCamelCase						:						Any       ):



									'''simple docstring'''






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






						def       __lowerCAmelCase(   self						:						Tuple					,   __UpperCamelCase						:						str       ):



									'''simple docstring'''






									snake_case__          =						self.language_code_re.match(__UpperCamelCase       )
									snake_case__          =						[match.group(0       )] if match else []
									return code, self.language_code_re.sub(""""""					,   __UpperCamelCase       )






						def       __lowerCAmelCase(   self						:						Optional[int]					,   __UpperCamelCase						:						str       ):



									'''simple docstring'''






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






						def       __lowerCAmelCase(   self						:						Union[str, Any]					,   __UpperCamelCase						:						int       ):



									'''simple docstring'''






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






						def       __lowerCAmelCase(   self						:						Union[str, Any]					,   __UpperCamelCase						:						Dict					,   **__UpperCamelCase						:						Optional[Any]       ):



									'''simple docstring'''






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






						def       __lowerCAmelCase(   self						:						int					,   __UpperCamelCase						:						List[Any]					,   **__UpperCamelCase						:						List[Any]       ):



									'''simple docstring'''






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






						def       __lowerCAmelCase(   self						:						int					,   __UpperCamelCase						:						List[str]       ):



									'''simple docstring'''






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






						def       __lowerCAmelCase(   self						:						Optional[int]					,   __UpperCamelCase						:						List[Any]					,   __UpperCamelCase						:						Optional[int]=None       ):



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



									'''simple docstring'''






									snake_case__          =						self.spm_source
									snake_case__          =						self.encoder






						def       __lowerCAmelCase(   self						:						Optional[Any]       ):



									'''simple docstring'''






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






						@property
						def       __lowerCAmelCase(   self						:						str       ):



									'''simple docstring'''






									return len(self.encoder       )






						def       __lowerCAmelCase(   self						:						int					,   __UpperCamelCase						:						str					,   __UpperCamelCase						:						Optional[str] = None       ):



									'''simple docstring'''






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

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

									return tuple(__UpperCamelCase       )






						def       __lowerCAmelCase(   self						:						Any       ):



									'''simple docstring'''






									return self.get_src_vocab()






						def       __lowerCAmelCase(   self						:						int       ):



									'''simple docstring'''






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






						def       __lowerCAmelCase(   self						:						Optional[Any]       ):



									'''simple docstring'''






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






						def __getstate__(   self						:						int       ):



									'''simple docstring'''






									snake_case__          =						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						:						Optional[int]					,   __UpperCamelCase						:						Dict       ):



									'''simple docstring'''






									snake_case__          =						d

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

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






						def       __lowerCAmelCase(   self						:						Optional[int]					,   *__UpperCamelCase						:						Optional[Any]					,   **__UpperCamelCase						:						Any       ):



									'''simple docstring'''






									return 1






						def       __lowerCAmelCase(   self						:						Dict					,   __UpperCamelCase						:						int       ):



									'''simple docstring'''






									snake_case__          =						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       __lowerCAmelCase(   self						:						List[str]					,   __UpperCamelCase						:						List					,   __UpperCamelCase						:						Optional[List] = None					,   __UpperCamelCase						:						bool = False       ):



									'''simple docstring'''






									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    snake_case__     (  a       ,      a	)			->       sentencepiece.SentencePieceProcessor:





			'''simple docstring'''






			snake_case__          =						sentencepiece.SentencePieceProcessor(**a	)
			spm.Load(a	)
			return spm




def    snake_case__     (  a       ,      a	)			->       None:





			'''simple docstring'''






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




def    snake_case__     (  a	)			->       Union[Dict, List]:





			'''simple docstring'''






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




'''simple docstring'''
from __future__ import annotations


def 	lowercase_						( lowerCAmelCase__						:	int      ,				lowerCAmelCase__						:	int      ,				lowerCAmelCase__						:	int			):

			"""simple docstring"""





			assert (
			    c % greatest_common_divisor(lowerCAmelCase__      ,				lowerCAmelCase__			) == 0
			)  # greatest_common_divisor(a,b) function implemented below
			((__UpperCAmelCase)					,	(__UpperCAmelCase)					,	(__UpperCAmelCase)) :   int    					=  extended_gcd(lowerCAmelCase__      ,				lowerCAmelCase__			)  # extended_gcd(a,b) function implemented below
			__UpperCAmelCase :   Union[str, Any]    					=  c / d
			return (r * x, r * y)


def 	lowercase_						( lowerCAmelCase__						:	int      ,				lowerCAmelCase__						:	int      ,				lowerCAmelCase__						:	int      ,				lowerCAmelCase__						:	int = 2			):

			"""simple docstring"""





			((__UpperCAmelCase)					,	(__UpperCAmelCase)) :   List[str]    					=  diophantine(lowerCAmelCase__      ,				lowerCAmelCase__      ,				lowerCAmelCase__			)  # Initial value
			__UpperCAmelCase :   List[str]    					=  greatest_common_divisor(lowerCAmelCase__      ,				lowerCAmelCase__			)
			__UpperCAmelCase :   List[str]    					=  a // d
			__UpperCAmelCase :   Tuple    					=  b // d

			for i in range(lowerCAmelCase__			):
						__UpperCAmelCase :   List[Any]    					=  xa + i * q
						__UpperCAmelCase :   Tuple    					=  ya - i * p
						print(lowerCAmelCase__      ,				lowerCAmelCase__			)


def 	lowercase_						( lowerCAmelCase__						:	int      ,				lowerCAmelCase__						:	int			):

			"""simple docstring"""





			if a < b:
						__UpperCAmelCase					,	__UpperCAmelCase :   List[str]    					=  b, a

			while a % b != 0:
						__UpperCAmelCase					,	__UpperCAmelCase :   Optional[int]    					=  b, a % b

			return b


def 	lowercase_						( lowerCAmelCase__						:	int      ,				lowerCAmelCase__						:	int			):

			"""simple docstring"""





			assert a >= 0 and b >= 0

			if b == 0:
						__UpperCAmelCase					,	__UpperCAmelCase					,	__UpperCAmelCase :   List[str]    					=  a, 1, 0
			else:
						((__UpperCAmelCase)					,	(__UpperCAmelCase)					,	(__UpperCAmelCase)) :   str    					=  extended_gcd(lowerCAmelCase__      ,				a % b			)
						__UpperCAmelCase :   Optional[Any]    					=  q
						__UpperCAmelCase :   Dict    					=  p - q * (a // b)

			assert a % d == 0 and b % d == 0
			assert d == a * x + b * y

			return (d, x, y)


if __name__ == "__main__":
					from doctest import testmod

					testmod(name='''diophantine''', verbose=True)
					testmod(name='''diophantine_all_soln''', verbose=True)
					testmod(name='''extended_gcd''', verbose=True)
					testmod(name='''greatest_common_divisor''', verbose=True)




