





"""simple docstring"""


import os
from shutil import copyfile
from typing import TYPE_CHECKING, Optional, Tuple

from tokenizers import processors

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
from ...utils.versions import require_version


if TYPE_CHECKING:
   from transformers.pipelines.conversational import Conversation

require_version("""tokenizers>=0.13.3""")

if is_sentencepiece_available():
   from .tokenization_llama import LlamaTokenizer
else:
   a__    :   Tuple    						= None

a__    :   Any    						= logging.get_logger(__name__)
a__    :   Optional[int]    						= {"""vocab_file""": """tokenizer.model""", """tokenizer_file""": """tokenizer.json"""}

a__						,       a__    :   str    						= """[INST]""", """[/INST]"""
a__						,       a__    :   List[Any]    						= """<<SYS>>\n""", """\n<</SYS>>\n\n"""

# fmt: off
a__    :   Union[str, Any]    						= """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\
answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\
that your responses are socially unbiased and positive in nature.

If a question does not make any sense, or is not factually coherent, explain why instead of answering something not\
correct. If you don't know the answer to a question, please don't share false information."""



class    lowercase_ (   __lowerCAmelCase							):
       snake_case__ :							List[str] 							=   VOCAB_FILES_NAMES
       snake_case__ :							Optional[Any] 							=   LlamaTokenizer
       snake_case__ :							Optional[Any] 							=   """left"""
       snake_case__ :							List[Any] 							=   ["""input_ids""", """attention_mask"""]

       def __init__(	self      ,    __SCREAMING_SNAKE_CASE=None      ,    __SCREAMING_SNAKE_CASE=None      ,    __SCREAMING_SNAKE_CASE=False      ,    __SCREAMING_SNAKE_CASE="<unk>"      ,    __SCREAMING_SNAKE_CASE="<s>"      ,    __SCREAMING_SNAKE_CASE="</s>"      ,    __SCREAMING_SNAKE_CASE=True      ,    __SCREAMING_SNAKE_CASE=False      ,    **__SCREAMING_SNAKE_CASE      ,    ):






        '''simple docstring'''

        super().__init__(
            vocab_file=__SCREAMING_SNAKE_CASE      ,    tokenizer_file=__SCREAMING_SNAKE_CASE      ,    clean_up_tokenization_spaces=__SCREAMING_SNAKE_CASE      ,    unk_token=__SCREAMING_SNAKE_CASE      ,    bos_token=__SCREAMING_SNAKE_CASE      ,    eos_token=__SCREAMING_SNAKE_CASE      ,    **__SCREAMING_SNAKE_CASE      ,    )
        snake_case__										= add_bos_token
        snake_case__										= add_eos_token
        self.update_post_processor()

        snake_case__										= vocab_file
        snake_case__										= False if not self.vocab_file else True

       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        snake_case__										= self.bos_token
        snake_case__										= self.bos_token_id

        snake_case__										= self.eos_token
        snake_case__										= self.eos_token_id

        snake_case__										= F"{(bos+':0 ') * self.add_bos_token}$A:0{(' '+eos+':0') * self.add_eos_token}"
        snake_case__										= F"{single}{(' '+bos+':1') * self.add_bos_token} $B:1{(' '+eos+':1') * self.add_eos_token}"

        snake_case__										= []
        if self.add_bos_token:
         special_tokens.append((bos, bos_token_id)   )
        if self.add_eos_token:
         special_tokens.append((eos, eos_token_id)   )
        snake_case__										= processors.TemplateProcessing(
            single=__SCREAMING_SNAKE_CASE      ,    pair=__SCREAMING_SNAKE_CASE      ,    special_tokens=__SCREAMING_SNAKE_CASE   )

       @property
       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        return self._add_eos_token

       @property
       def 						_SCREAMING_SNAKE_CASE(	self   ):






        '''simple docstring'''

        return self._add_bos_token

       @add_eos_token.setter
       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        snake_case__										= value
        self.update_post_processor()

       @add_bos_token.setter
       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        snake_case__										= value
        self.update_post_processor()

       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE      ,    __SCREAMING_SNAKE_CASE = None   ):






        '''simple docstring'''

        if not self.can_save_slow_tokenizer:
         raise ValueError(
             "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
             "tokenizer."   )

        if not os.path.isdir(__SCREAMING_SNAKE_CASE   ):
         logger.error(F"Vocabulary path ({save_directory}) should be a directory"   )
         return
        snake_case__										= os.path.join(
            __SCREAMING_SNAKE_CASE      ,    (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]   )

        if os.path.abspath(self.vocab_file   ) != os.path.abspath(__SCREAMING_SNAKE_CASE   ):
         copyfile(self.vocab_file      ,    __SCREAMING_SNAKE_CASE   )

        return (out_vocab_file,)

       def 						_SCREAMING_SNAKE_CASE(	self      ,    __SCREAMING_SNAKE_CASE   ):






        '''simple docstring'''

        snake_case__										= list(conversation.iter_texts()   )
        if not all([is_user for is_user, msg in dialogue[::2]]   ) or not all(
            [not is_user for is_user, msg in dialogue[1::2]]   ):
         raise ValueError(
             "The model only supports 'user' and 'assistant' roles, starting with user and alternating (u/a/u/a/u...)"   )

        snake_case__										= []
        if len(conversation.past_user_inputs   ) > 0:
         if not conversation.past_user_inputs[0].startswith(__SCREAMING_SNAKE_CASE   ) or E_SYS not in conversation.past_user_inputs[0]:
          snake_case__										= (
              B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
          )
        elif not dialogue[0][1].startswith(__SCREAMING_SNAKE_CASE   ) or E_SYS not in dialogue[0][1]:
         snake_case__										= (dialogue[0][0], B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + dialogue[0][1])

        dialog_tokens += sum(
            [
                [self.bos_token_id]
                + self.encode(
                    F"{B_INST} {(prompt[1]).strip()} {E_INST} {(answer[1]).strip()} "      ,    add_special_tokens=__SCREAMING_SNAKE_CASE   )
                + [self.eos_token_id]
                for prompt, answer in zip(dialogue[::2]      ,    dialogue[1::2]   )
            ]      ,    []      ,    )
        if not (dialogue[-1][0]):
         raise ValueError(F"Last message must be from user, got {dialogue[-1]['role']}"   )
        dialog_tokens += [self.bos_token_id] + self.encode(
            F"{B_INST} {(dialogue[-1][1]).strip()} {E_INST}"      ,    add_special_tokens=__SCREAMING_SNAKE_CASE   )
        return dialog_tokens








"""simple docstring"""


import random
import sys

from . import cryptomath_module as cryptomath

a__    :   int    						= (
    r""" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`"""
    r"""abcdefghijklmnopqrstuvwxyz{|}~"""
)





def 							a__	(     _UpperCAmelCase		,   _UpperCAmelCase		,   _UpperCAmelCase		)			->     None:

 '''simple docstring'''






 if mode == "encrypt":
  if key_a == 1:
   sys.exit(
       "The affine cipher becomes weak when key "
       "A is set to 1. Choose different key"		)
  if key_b == 0:
   sys.exit(
       "The affine cipher becomes weak when key "
       "B is set to 0. Choose different key"		)
 if key_a < 0 or key_b < 0 or key_b > len(_UpperCAmelCase		) - 1:
  sys.exit(
      "Key A must be greater than 0 and key B must "
      f"be between 0 and {len(_UpperCAmelCase		) - 1}."		)
 if cryptomath.gcd(_UpperCAmelCase		,   len(_UpperCAmelCase		)		) != 1:
  sys.exit(
      f"Key A {key_a} and the symbol set size {len(_UpperCAmelCase		)} "
      "are not relatively prime. Choose a different key."		)





def 							a__	(     _UpperCAmelCase		,   _UpperCAmelCase		)			->     str:

 '''simple docstring'''






 snake_case__							,      snake_case__										= divmod(_UpperCAmelCase		,   len(_UpperCAmelCase		)		)
 check_keys(_UpperCAmelCase		,   _UpperCAmelCase		,   "encrypt"		)
 snake_case__										= ""
 for symbol in message:
  if symbol in SYMBOLS:
   snake_case__										= SYMBOLS.find(_UpperCAmelCase		)
   cipher_text += SYMBOLS[(sym_index * key_a + key_b) % len(_UpperCAmelCase		)]
  else:
   cipher_text += symbol
 return cipher_text





def 							a__	(     _UpperCAmelCase		,   _UpperCAmelCase		)			->     str:

 '''simple docstring'''






 snake_case__							,      snake_case__										= divmod(_UpperCAmelCase		,   len(_UpperCAmelCase		)		)
 check_keys(_UpperCAmelCase		,   _UpperCAmelCase		,   "decrypt"		)
 snake_case__										= ""
 snake_case__										= cryptomath.find_mod_inverse(_UpperCAmelCase		,   len(_UpperCAmelCase		)		)
 for symbol in message:
  if symbol in SYMBOLS:
   snake_case__										= SYMBOLS.find(_UpperCAmelCase		)
   plain_text += SYMBOLS[
       (sym_index - key_b) * mod_inverse_of_key_a % len(_UpperCAmelCase		)
   ]
  else:
   plain_text += symbol
 return plain_text





def 							a__	(     )			->     int:

 '''simple docstring'''






 while True:
  snake_case__										= random.randint(2		,   len(_UpperCAmelCase		)		)
  snake_case__										= random.randint(2		,   len(_UpperCAmelCase		)		)
  if cryptomath.gcd(_UpperCAmelCase		,   len(_UpperCAmelCase		)		) == 1 and key_b % len(_UpperCAmelCase		) != 0:
   return key_b * len(_UpperCAmelCase		) + key_b





def 							a__	(     )			->     None:

 '''simple docstring'''






 snake_case__										= input("Enter message: "		).strip()
 snake_case__										= int(input("Enter key [2000 - 9000]: "		).strip()		)
 snake_case__										= input("Encrypt/Decrypt [E/D]: "		).strip().lower()

 if mode.startswith("e"		):
  snake_case__										= "encrypt"
  snake_case__										= encrypt_message(_UpperCAmelCase		,   _UpperCAmelCase		)
 elif mode.startswith("d"		):
  snake_case__										= "decrypt"
  snake_case__										= decrypt_message(_UpperCAmelCase		,   _UpperCAmelCase		)
 print(f"\n{mode.title()}ed text: \n{translated}"		)


if __name__ == "__main__":
   import doctest

   doctest.testmod()
   # main()

