


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

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

a_       :     Optional[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_       :     Union[str, Any] 							=     {'Helsinki-NLP/opus-mt-en-de': 5_1_2}
a_       :     Optional[Any] 							=     {}




class 			a  (  _SCREAMING_SNAKE_CASE							):
 _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   ,					__magic_name__   ,					__magic_name__   ,					__magic_name__   ,					__magic_name__=None   ,					__magic_name__=None   ,					__magic_name__=None   ,					__magic_name__="<unk>"   ,					__magic_name__="</s>"   ,					__magic_name__="<pad>"   ,					__magic_name__=5_12   ,					__magic_name__ = None   ,					__magic_name__=False   ,					**__magic_name__   ,					)       ->				List[Any]:
      _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=__magic_name__   ,					target_lang=__magic_name__   ,					unk_token=__magic_name__   ,					eos_token=__magic_name__   ,					pad_token=__magic_name__   ,					model_max_length=__magic_name__   ,					sp_model_kwargs=self.sp_model_kwargs   ,					target_vocab_file=__magic_name__   ,					separate_vocabs=__magic_name__   ,					**__magic_name__   ,					)
      assert Path(__magic_name__    ).exists(), f'cannot find spm source {source_spm}'

      _a         =				separate_vocabs
      _a         =				load_json(__magic_name__    )
      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(__magic_name__    )
           _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(__magic_name__   ,					self.sp_model_kwargs    )
      _a         =				load_spm(__magic_name__   ,					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 				__UpperCAmelCase		(			self    )       ->				List[Any]:




      try:
           from sacremoses import MosesPunctNormalizer

           _a         =				MosesPunctNormalizer(self.source_lang    ).normalize
      except (ImportError, FileNotFoundError):
           warnings.warn('Recommended: pip install sacremoses.'    )
           _a         =				lambda __magic_name__    : x
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				Optional[int]:
      return self.punc_normalizer(__magic_name__    ) if x else ""
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				Optional[Any]:
      return self.current_encoder.get(__magic_name__   ,					self.current_encoder[self.unk_token]    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				Optional[int]:
      _a         =				self.language_code_re.match(__magic_name__    )
      _a         =				[match.group(0    )] if match else []
      return code, self.language_code_re.sub(''   ,					__magic_name__    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				List[Any]:
      _a         =				self.remove_language_code(__magic_name__    )
      _a         =				self.current_spm.encode(__magic_name__   ,					out_type=__magic_name__    )
      return code + pieces
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				Any:
      return self.decoder.get(__magic_name__   ,					self.unk_token    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					**__magic_name__    )       ->				Any:
      return super().batch_decode(__magic_name__   ,					**__magic_name__    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					**__magic_name__    )       ->				List[str]:
      return super().decode(__magic_name__   ,					**__magic_name__    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				Union[str, Any]:
      _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(__magic_name__    ) + token + " "
                _a         =				[]
           else:
                current_sub_tokens.append(__magic_name__    )
      out_string += sp_model.decode_pieces(__magic_name__    )
      return out_string.strip()
 def 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					__magic_name__=None    )       ->				Union[str, Any]:




      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    )       ->				List[str]:
      _a         =				self.spm_source
      _a         =				self.encoder
 def 				__UpperCAmelCase		(			self    )       ->				Optional[int]:
      _a         =				self.spm_target
      if self.separate_vocabs:
           _a         =				self.target_encoder
 @property
 def 				__UpperCAmelCase		(			self    )       ->				Tuple:
      return len(self.encoder    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					__magic_name__ = None    )       ->				Dict:




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

      if self.separate_vocabs:
           _a         =				os.path.join(
               __magic_name__   ,					(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab']   ,					)
           _a         =				os.path.join(
               __magic_name__   ,					(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['target_vocab_file']   ,					)
           save_json(self.encoder   ,					__magic_name__    )
           save_json(self.target_encoder   ,					__magic_name__    )
           saved_files.append(__magic_name__    )
           saved_files.append(__magic_name__    )
      else:
           _a         =				os.path.join(
               __magic_name__   ,					(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab']    )
           save_json(self.encoder   ,					__magic_name__    )
           saved_files.append(__magic_name__    )

      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(
               __magic_name__   ,					(filename_prefix + '-' if filename_prefix else '') + spm_save_filename    )
           if os.path.abspath(__magic_name__    ) != os.path.abspath(__magic_name__    ) and os.path.isfile(__magic_name__    ):
                copyfile(__magic_name__   ,					__magic_name__    )
                saved_files.append(__magic_name__    )
           elif not os.path.isfile(__magic_name__    ):
                with open(__magic_name__   ,					'wb'    ) as fi:
                     _a         =				spm_model.serialized_model_proto()
                     fi.write(__magic_name__    )
                saved_files.append(__magic_name__    )

      return tuple(__magic_name__    )
 def 				__UpperCAmelCase		(			self    )       ->				Any:
      return self.get_src_vocab()
 def 				__UpperCAmelCase		(			self    )       ->				Tuple:
      return dict(self.encoder   ,					**self.added_tokens_encoder    )
 def 				__UpperCAmelCase		(			self    )       ->				str:
      return dict(self.target_encoder   ,					**self.added_tokens_decoder    )
 def __getstate__(			self    )       ->				Optional[int]:
      _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   ,					__magic_name__    )       ->				Any:
      _a         =				d

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

      _a         =				(load_spm(__magic_name__   ,					self.sp_model_kwargs    ) for f in self.spm_files)
      _a         =				self.spm_source
      self._setup_normalizer()
 def 				__UpperCAmelCase		(			self   ,					*__magic_name__   ,					**__magic_name__    )       ->				Dict:
      return 1
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				Dict:
      _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 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					__magic_name__ = None   ,					__magic_name__ = False    )       ->				Dict:




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






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




     '''simple docstring'''



     _a         =				sentencepiece.SentencePieceProcessor(**A_		)
     spm.Load(A_		)
     return spm






def 						_A					(lowerCAmelCase__	:int					,    lowerCAmelCase__	:str		) ->	List[Any]:




     '''simple docstring'''



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






def 						_A					(lowerCAmelCase__	:str		) ->	str:




     '''simple docstring'''



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









"""simple docstring"""


from doctest import testmod
from math import sqrt




def      snake_case    (A_ :int ):







  '''simple docstring'''

  a	:     list[int]							=  []
  if num < 1:
    return facs
  facs.append(1 )
  if num == 1:
    return facs
  facs.append(A_ )
  for i in range(2      ,     int(sqrt(A_ ) ) + 1 ):
    if num % i == 0:  # If i is a factor of num
      facs.append(A_ )
      a	:     Optional[Any]							=  num // i  # num//i is the other factor of num
      if d != i:  # If d and i are distinct
        facs.append(A_ )  # we have found another factor
  facs.sort()
  return facs


if __name__ == "__main__":
   testmod(name='factors_of_a_number', verbose=True)




