




'''simple docstring'''





import os
from shutil import copyfile
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
  from transformers.pipelines.conversational import Conversation

a		:	str       =      logging.get_logger(__name__)

a		:	int       =      {'''vocab_file''': '''tokenizer.model'''}

a		:	Optional[Any]       =      {
    '''vocab_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer.model''',
    },
    '''tokenizer_file''': {
        '''hf-internal-testing/llama-tokenizer''': '''https://huggingface.co/hf-internal-testing/llama-tokenizer/resolve/main/tokenizer_config.json''',
    },
}
a		:	Optional[int]       =      {
    '''hf-internal-testing/llama-tokenizer''': 2_0_4_8,
}
a		:	Optional[Any]       =      '''▁'''

a      ,				a		:	Optional[Any]       =      '''[INST]''', '''[/INST]'''
a      ,				a		:	Optional[Any]       =      '''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
a		:	int       =      '''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      UpperCamelCase       (	snake_case__       ):
  a     :Dict          =					VOCAB_FILES_NAMES
  a     :Any          =					PRETRAINED_VOCAB_FILES_MAP
  a     :Optional[int]          =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  a     :Optional[Any]          =					['input_ids', 'attention_mask']



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







      '''simple docstring'''


      _a				:							Dict							       =      {} if sp_model_kwargs is None else sp_model_kwargs
      _a				:							Any							       =      AddedToken(__lowerCAmelCase		,     lstrip=__lowerCAmelCase		,     rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase		,     __lowerCAmelCase ) else bos_token
      _a				:							Optional[Any]							       =      AddedToken(__lowerCAmelCase		,     lstrip=__lowerCAmelCase		,     rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase		,     __lowerCAmelCase ) else eos_token
      _a				:							Dict							       =      AddedToken(__lowerCAmelCase		,     lstrip=__lowerCAmelCase		,     rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase		,     __lowerCAmelCase ) else unk_token
      _a				:							Union[str, Any]							       =      AddedToken(__lowerCAmelCase		,     lstrip=__lowerCAmelCase		,     rstrip=__lowerCAmelCase ) if isinstance(__lowerCAmelCase		,     __lowerCAmelCase ) else pad_token
      super().__init__(
          bos_token=__lowerCAmelCase		,     eos_token=__lowerCAmelCase		,     unk_token=__lowerCAmelCase		,     pad_token=__lowerCAmelCase		,     add_bos_token=__lowerCAmelCase		,     add_eos_token=__lowerCAmelCase		,     sp_model_kwargs=self.sp_model_kwargs		,     clean_up_tokenization_spaces=__lowerCAmelCase		,     legacy=__lowerCAmelCase		,     **__lowerCAmelCase		,     )
      if legacy:
          logger.warning_once(
              f'''You are using the legacy behaviour of the {self.__class__}. This means that tokens that come after special tokens will not be properly handled. We recommend you to'''
              """ read the related pull request available at https://github.com/huggingface/transformers/pull/24565""" )
      _a				:							Optional[Any]							       =      legacy
      _a				:							Dict							       =      vocab_file
      _a				:							Optional[Any]							       =      add_bos_token
      _a				:							int							       =      add_eos_token
      _a				:							Optional[int]							       =      spm.SentencePieceProcessor(**self.sp_model_kwargs )
      self.sp_model.Load(__lowerCAmelCase )



  def __getstate__(			self ):







      '''simple docstring'''


      _a				:							Any							       =      self.__dict__.copy()
      _a				:							Tuple							       =      None
      _a				:							Any							       =      self.sp_model.serialized_model_proto()
      return state



  def __setstate__(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							List[str]							       =      d
      _a				:							int							       =      spm.SentencePieceProcessor(**self.sp_model_kwargs )
      self.sp_model.LoadFromSerializedProto(self.sp_model_proto )



  @property
  def     a_							(			self ):







      '''simple docstring'''


      return self.sp_model.get_piece_size()



  def     a_							(			self ):







      '''simple docstring'''


      _a				:							Tuple							       =      {self.convert_ids_to_tokens(__lowerCAmelCase ): i for i in range(self.vocab_size )}
      vocab.update(self.added_tokens_encoder )
      return vocab



  def     a_							(			self		,     __lowerCAmelCase		,     **__lowerCAmelCase ):







      '''simple docstring'''


      if not self.legacy:
          _a				:							Optional[Any]							       =      SPIECE_UNDERLINE + text.replace(__lowerCAmelCase		,     """ """ )
      return super().tokenize(__lowerCAmelCase		,     **__lowerCAmelCase )



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      if not self.legacy:
          _a				:							str							       =      text.startswith(__lowerCAmelCase )
          if is_first:
              _a				:							Optional[Any]							       =      text[1:]

      _a				:							List[Any]							       =      self.sp_model.encode(__lowerCAmelCase		,     out_type=__lowerCAmelCase )

      if not self.legacy and not is_first and not text.startswith(""" """ ) and tokens[0].startswith(__lowerCAmelCase ):
          _a				:							Union[str, Any]							       =      ([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
      return tokens



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      return self.sp_model.piece_to_id(__lowerCAmelCase )



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							Any							       =      self.sp_model.IdToPiece(__lowerCAmelCase )
      return token



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							List[str]							       =      []
      _a				:							Any							       =      """"""
      _a				:							str							       =      False
      for i, token in enumerate(__lowerCAmelCase ):
          # make sure that special tokens are not decoded using sentencepiece model
          if token in self.all_special_tokens:
              if not prev_is_special and i != 0:
                  out_string += " "
              out_string += self.sp_model.decode(__lowerCAmelCase ) + token
              _a				:							List[str]							       =      True
              _a				:							str							       =      []
          else:
              current_sub_tokens.append(__lowerCAmelCase )
              _a				:							Union[str, Any]							       =      False
      out_string += self.sp_model.decode(__lowerCAmelCase )
      return out_string



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase = None ):







      '''simple docstring'''


      if not os.path.isdir(__lowerCAmelCase ):
          logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' )
          return
      _a				:							Optional[int]							       =      os.path.join(
          __lowerCAmelCase		,     (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""] )

      if os.path.abspath(self.vocab_file ) != os.path.abspath(__lowerCAmelCase ) and os.path.isfile(self.vocab_file ):
          copyfile(self.vocab_file		,     __lowerCAmelCase )
      elif not os.path.isfile(self.vocab_file ):
          with open(__lowerCAmelCase		,     """wb""" ) as fi:
              _a				:							Dict							       =      self.sp_model.serialized_model_proto()
              fi.write(__lowerCAmelCase )

      return (out_vocab_file,)



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase=None ):







      '''simple docstring'''


      _a				:							List[Any]							       =      [self.bos_token_id] if self.add_bos_token else []
      _a				:							int							       =      [self.eos_token_id] if self.add_eos_token else []

      _a				:							Tuple							       =      bos_token_id + token_ids_a + eos_token_id

      if token_ids_a is not None:
          _a				:							Optional[int]							       =      output + bos_token_id + token_ids_a + eos_token_id

      return output



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase = None		,     __lowerCAmelCase = False ):







      '''simple docstring'''


      if already_has_special_tokens:
          return super().get_special_tokens_mask(
              token_ids_a=__lowerCAmelCase		,     token_ids_a=__lowerCAmelCase		,     already_has_special_tokens=__lowerCAmelCase )

      _a				:							Any							       =      [1] if self.add_bos_token else []
      _a				:							Dict							       =      [1] if self.add_eos_token else []

      if token_ids_a is None:
          return bos_token_id + ([0] * len(__lowerCAmelCase )) + eos_token_id
      return (
          bos_token_id
          + ([0] * len(__lowerCAmelCase ))
          + eos_token_id
          + bos_token_id
          + ([0] * len(__lowerCAmelCase ))
          + eos_token_id
      )



  def     a_							(			self		,     __lowerCAmelCase		,     __lowerCAmelCase = None ):







      '''simple docstring'''


      _a				:							Any							       =      [self.bos_token_id] if self.add_bos_token else []
      _a				:							Optional[Any]							       =      [self.eos_token_id] if self.add_eos_token else []

      _a				:							Optional[Any]							       =      [0] * len(bos_token_id + token_ids_a + eos_token_id )

      if token_ids_a is not None:
          output += [1] * len(bos_token_id + token_ids_a + eos_token_id )

      return output



  def     a_							(			self		,     __lowerCAmelCase ):







      '''simple docstring'''


      _a				:							Union[str, Any]							       =      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...)""" )

      _a				:							List[int]							       =      []
      if len(conversation.past_user_inputs ) > 0:
          if not conversation.past_user_inputs[0].startswith(__lowerCAmelCase ) or E_SYS not in conversation.past_user_inputs[0]:
              _a				:							Optional[int]							       =      (
                  B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
              )
      elif not dialogue[0][1].startswith(__lowerCAmelCase ) or E_SYS not in dialogue[0][1]:
          _a				:							str							       =      (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=__lowerCAmelCase )
              + [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=__lowerCAmelCase )
      return dialog_tokens








import requests

try:
							from django.contrib.auth import authenticate, login
							from django.shortcuts import redirect, render
except ImportError:
							UpperCamelCase__						=		UpperCamelCase__						=		UpperCamelCase__						=		UpperCamelCase__						=		print






def    snake_case   (				A     )				->				List[str]:




	'''simple docstring'''


	lowerCamelCase_				:						Optional[int]				  =				'secretKey'
	lowerCamelCase_				:						str				  =				'https://www.google.com/recaptcha/api/siteverify'

	# when method is not POST, direct user to login page
	if request.method != "POST":
		return render(A		,  'login.html'     )

	# from the frontend, get username, password, and client_key
	lowerCamelCase_				:						int				  =				request.POST.get('username'     )
	lowerCamelCase_				:						str				  =				request.POST.get('password'     )
	lowerCamelCase_				:						List[Any]				  =				request.POST.get('g-recaptcha-response'     )

	# post recaptcha response to Google's recaptcha api
	lowerCamelCase_				:						Union[str, Any]				  =				requests.post(A		,  data={'secret': secret_key, 'response': client_key}     )
	# if the recaptcha api verified our keys
	if response.json().get('success'		,  A     ):
		# authenticate the user
		lowerCamelCase_				:						int				  =				authenticate(A		,  username=A		,  password=A     )
		if user_in_database:
			login(A		,  A     )
			return redirect('/your-webpage'     )
	return render(A		,  'login.html'     )
