




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

class  __lowercase    (     lowerCamelCase_		):


				'''simple docstring'''


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

				def __init__(				self				:       int ,SCREAMING_SNAKE_CASE_				:       Optional[int] ,SCREAMING_SNAKE_CASE_				:       Dict ,SCREAMING_SNAKE_CASE_				:       str ,SCREAMING_SNAKE_CASE_				:       int=None ,SCREAMING_SNAKE_CASE_				:       Tuple=None ,SCREAMING_SNAKE_CASE_				:       str=None ,SCREAMING_SNAKE_CASE_				:       Tuple="<unk>" ,SCREAMING_SNAKE_CASE_				:       Dict="</s>" ,SCREAMING_SNAKE_CASE_				:       List[Any]="<pad>" ,SCREAMING_SNAKE_CASE_				:       List[str]=5_1_2 ,SCREAMING_SNAKE_CASE_				:       Union[str, Any] = None ,SCREAMING_SNAKE_CASE_				:       Union[str, Any]=False ,**SCREAMING_SNAKE_CASE_				:       Optional[int] ,):
										snake_case__    :   Optional[int]							     =   {} 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=SCREAMING_SNAKE_CASE_ ,target_lang=SCREAMING_SNAKE_CASE_ ,unk_token=SCREAMING_SNAKE_CASE_ ,eos_token=SCREAMING_SNAKE_CASE_ ,pad_token=SCREAMING_SNAKE_CASE_ ,model_max_length=SCREAMING_SNAKE_CASE_ ,sp_model_kwargs=self.sp_model_kwargs ,target_vocab_file=SCREAMING_SNAKE_CASE_ ,separate_vocabs=SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ ,)
										assert Path(SCREAMING_SNAKE_CASE_ ).exists(), F'''cannot find spm source {source_spm}'''

										snake_case__    :   Union[str, Any]							     =   separate_vocabs
										snake_case__    :   Union[str, Any]							     =   load_json(SCREAMING_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:
																snake_case__    :   Dict							     =   load_json(SCREAMING_SNAKE_CASE_ )
																snake_case__    :   Tuple							     =   {v: k for k, v in self.target_encoder.items()}
																snake_case__    :   int							     =   []
										else:
																snake_case__    :   Dict							     =   {v: k for k, v in self.encoder.items()}
																snake_case__    :   list							     =   [k for k in self.encoder if k.startswith('''>>''' ) and k.endswith('''<<''' )]

										snake_case__    :   int							     =   source_lang
										snake_case__    :   Optional[Any]							     =   target_lang
										snake_case__    :   Any							     =   [source_spm, target_spm]

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

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

										self._setup_normalizer()

				def  _lowerCamelCase   (				self				:       int ):







										try:
																from sacremoses import MosesPunctNormalizer

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

				def  _lowerCamelCase   (				self				:       Union[str, Any] ,SCREAMING_SNAKE_CASE_				:       Any ):
										return self.punc_normalizer(SCREAMING_SNAKE_CASE_ ) if x else ""

				def  _lowerCamelCase   (				self				:       Dict ,SCREAMING_SNAKE_CASE_				:       List[str] ):
										return self.current_encoder.get(SCREAMING_SNAKE_CASE_ ,self.current_encoder[self.unk_token] )

				def  _lowerCamelCase   (				self				:       Optional[int] ,SCREAMING_SNAKE_CASE_				:       int ):
										snake_case__    :   Tuple							     =   self.language_code_re.match(SCREAMING_SNAKE_CASE_ )
										snake_case__    :   list							     =   [match.group(0 )] if match else []
										return code, self.language_code_re.sub('''''' ,SCREAMING_SNAKE_CASE_ )

				def  _lowerCamelCase   (				self				:       List[str] ,SCREAMING_SNAKE_CASE_				:       str ):
										snake_case__    :   str							     =   self.remove_language_code(SCREAMING_SNAKE_CASE_ )
										snake_case__    :   int							     =   self.current_spm.encode(SCREAMING_SNAKE_CASE_ ,out_type=SCREAMING_SNAKE_CASE_ )
										return code + pieces

				def  _lowerCamelCase   (				self				:       int ,SCREAMING_SNAKE_CASE_				:       Union[str, Any] ):
										return self.decoder.get(SCREAMING_SNAKE_CASE_ ,self.unk_token )

				def  _lowerCamelCase   (				self				:       List[Any] ,SCREAMING_SNAKE_CASE_				:       Optional[int] ,**SCREAMING_SNAKE_CASE_				:       Union[str, Any] ):
										return super().batch_decode(SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ )

				def  _lowerCamelCase   (				self				:       Dict ,SCREAMING_SNAKE_CASE_				:       List[str] ,**SCREAMING_SNAKE_CASE_				:       Union[str, Any] ):
										return super().decode(SCREAMING_SNAKE_CASE_ ,**SCREAMING_SNAKE_CASE_ )

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

				def  _lowerCamelCase   (				self				:       List[str] ,SCREAMING_SNAKE_CASE_				:       int ,SCREAMING_SNAKE_CASE_				:       Tuple=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  _lowerCamelCase   (				self				:       List[Any] ):
										snake_case__    :   Tuple							     =   self.spm_source
										snake_case__    :   Any							     =   self.encoder

				def  _lowerCamelCase   (				self				:       Tuple ):
										snake_case__    :   List[Any]							     =   self.spm_target
										if self.separate_vocabs:
																snake_case__    :   Union[str, Any]							     =   self.target_encoder

				@property
				def  _lowerCamelCase   (				self				:       Tuple ):
										return len(self.encoder )

				def  _lowerCamelCase   (				self				:       List[Any] ,SCREAMING_SNAKE_CASE_				:       List[Any] ,SCREAMING_SNAKE_CASE_				:       Optional[Any] = None ):







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

										if self.separate_vocabs:
																snake_case__    :   Any							     =   os.path.join(
																    SCREAMING_SNAKE_CASE_ ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab'''] ,)
																snake_case__    :   List[Any]							     =   os.path.join(
																    SCREAMING_SNAKE_CASE_ ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''target_vocab_file'''] ,)
																save_json(self.encoder ,SCREAMING_SNAKE_CASE_ )
																save_json(self.target_encoder ,SCREAMING_SNAKE_CASE_ )
																saved_files.append(SCREAMING_SNAKE_CASE_ )
																saved_files.append(SCREAMING_SNAKE_CASE_ )
										else:
																snake_case__    :   int							     =   os.path.join(
																    SCREAMING_SNAKE_CASE_ ,(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab'''] )
																save_json(self.encoder ,SCREAMING_SNAKE_CASE_ )
																saved_files.append(SCREAMING_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] ,):
																snake_case__    :   List[str]							     =   os.path.join(
																    SCREAMING_SNAKE_CASE_ ,(filename_prefix + '''-''' if filename_prefix else '''''') + spm_save_filename )
																if os.path.abspath(SCREAMING_SNAKE_CASE_ ) != os.path.abspath(SCREAMING_SNAKE_CASE_ ) and os.path.isfile(SCREAMING_SNAKE_CASE_ ):
																						copyfile(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ )
																						saved_files.append(SCREAMING_SNAKE_CASE_ )
																elif not os.path.isfile(SCREAMING_SNAKE_CASE_ ):
																						with open(SCREAMING_SNAKE_CASE_ ,'''wb''' ) as fi:
																												snake_case__    :   List[str]							     =   spm_model.serialized_model_proto()
																												fi.write(SCREAMING_SNAKE_CASE_ )
																						saved_files.append(SCREAMING_SNAKE_CASE_ )

										return tuple(SCREAMING_SNAKE_CASE_ )

				def  _lowerCamelCase   (				self				:       Tuple ):
										return self.get_src_vocab()

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

				def  _lowerCamelCase   (				self				:       List[Any] ):
										return dict(self.target_encoder ,**self.added_tokens_decoder )

				def __getstate__(				self				:       Optional[int] ):
										snake_case__    :   List[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				:       Optional[int] ,SCREAMING_SNAKE_CASE_				:       Optional[int] ):
										snake_case__    :   Union[str, Any]							     =   d

										# for backward compatibility
										if not hasattr(self ,'''sp_model_kwargs''' ):
																snake_case__    :   Optional[int]							     =   {}

										snake_case__    :   Optional[int]							     =   (load_spm(SCREAMING_SNAKE_CASE_ ,self.sp_model_kwargs ) for f in self.spm_files)
										snake_case__    :   List[Any]							     =   self.spm_source
										self._setup_normalizer()

				def  _lowerCamelCase   (				self				:       List[str] ,*SCREAMING_SNAKE_CASE_				:       Tuple ,**SCREAMING_SNAKE_CASE_				:       Dict ):
										return 1

				def  _lowerCamelCase   (				self				:       List[Any] ,SCREAMING_SNAKE_CASE_				:       Union[str, Any] ):
										snake_case__    :   Union[str, Any]							     =   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				:       Any ,SCREAMING_SNAKE_CASE_				:       str ,SCREAMING_SNAKE_CASE_				:       Optional[int] = None ,SCREAMING_SNAKE_CASE_				:       str = False ):







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







def 						lowerCAmelCase							(	lowerCamelCase ,     lowerCamelCase						):
						'''simple docstring'''


						snake_case__    :   Optional[int]							     =   sentencepiece.SentencePieceProcessor(**lowercase__						)
						spm.Load(lowercase__						)
						return spm



def 						lowerCAmelCase							(	lowerCamelCase ,     lowerCamelCase						):
						'''simple docstring'''


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



def 						lowerCAmelCase							(	lowerCamelCase						):
						'''simple docstring'''


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








"""simple docstring"""





from __future__ import annotations

import math
import random

def 						lowerCAmelCase							(	lowerCamelCase ,     lowerCamelCase ,     lowerCamelCase						):
						'''simple docstring'''


						snake_case__    :   Tuple							     =   d * e - 1
						snake_case__    :   Optional[int]							     =   0
						snake_case__    :   Tuple							     =   0
						while p == 0:
												snake_case__    :   Optional[int]							     =   random.randint(2 ,     n - 1						)
												snake_case__    :   Tuple							     =   k
												while True:
																		if t % 2 == 0:
																								snake_case__    :   List[Any]							     =   t // 2
																								snake_case__    :   Union[str, Any]							     =   (g**t) % n
																								snake_case__    :   Dict							     =   math.gcd(x - 1 ,     lowerCamelCase						)
																								if x > 1 and y > 1:
																														snake_case__    :   Union[str, Any]							     =   y
																														snake_case__    :   str							     =   n // y
																														break  # find the correct factors
																		else:
																								break  # t is not divisible by 2, break and choose another g
						return sorted([p, q]						)


if __name__ == "__main__":
							import doctest

							doctest.testmod()


