
"""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

UpperCamelCase      :							Any          =					logging.get_logger(__name__)

UpperCamelCase      :							List[Any]          =					{"vocab_file": "tokenizer.model"}

UpperCamelCase      :							List[str]          =					{
    "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",
    },
}
UpperCamelCase      :							Union[str, Any]          =					{
    "hf-internal-testing/llama-tokenizer": 2_0_4_8,
}
UpperCamelCase      :							Optional[int]          =					"▁"

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

# fmt: off
UpperCamelCase      :							Any          =					"You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your\\nanswers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure\\nthat your responses are socially unbiased and positive in nature.\n\nIf a question does not make any sense, or is not factually coherent, explain why instead of answering something not\\ncorrect. If you don\'t know the answer to a question, please don\'t share false information."

class __lowerCAmelCase						( lowerCAmelCase_     ):
     lowercase		  =		VOCAB_FILES_NAMES
     lowercase		  =		PRETRAINED_VOCAB_FILES_MAP
     lowercase		  =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     lowercase		  =		["""input_ids""", """attention_mask"""]





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

      '''simple docstring'''




      __UpperCamelCase							    =			{} if sp_model_kwargs is None else sp_model_kwargs
      __UpperCamelCase							    =			AddedToken(lowerCamelCase_      ,	lstrip=lowerCamelCase_      ,	rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_      ,	lowerCamelCase_ ) else bos_token
      __UpperCamelCase							    =			AddedToken(lowerCamelCase_      ,	lstrip=lowerCamelCase_      ,	rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_      ,	lowerCamelCase_ ) else eos_token
      __UpperCamelCase							    =			AddedToken(lowerCamelCase_      ,	lstrip=lowerCamelCase_      ,	rstrip=lowerCamelCase_ ) if isinstance(lowerCamelCase_      ,	lowerCamelCase_ ) else unk_token
      __UpperCamelCase							    =			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' )
      __UpperCamelCase							    =			legacy
      __UpperCamelCase							    =			vocab_file
      __UpperCamelCase							    =			add_bos_token
      __UpperCamelCase							    =			add_eos_token
      __UpperCamelCase							    =			spm.SentencePieceProcessor(**self.sp_model_kwargs )
      self.sp_model.Load(lowerCamelCase_ )





     def __getstate__(      self ):

      '''simple docstring'''




      __UpperCamelCase							    =			self.__dict__.copy()
      __UpperCamelCase							    =			None
      __UpperCamelCase							    =			self.sp_model.serialized_model_proto()
      return state





     def __setstate__(      self      ,	__UpperCAmelCase ):

      '''simple docstring'''




      __UpperCamelCase							    =			d
      __UpperCamelCase							    =			spm.SentencePieceProcessor(**self.sp_model_kwargs )
      self.sp_model.LoadFromSerializedProto(self.sp_model_proto )





     @property
     def 		UpperCAmelCase   (      self ):

      '''simple docstring'''




      return self.sp_model.get_piece_size()





     def 		UpperCAmelCase   (      self ):

      '''simple docstring'''




      __UpperCamelCase							    =			{self.convert_ids_to_tokens(lowerCamelCase_ ): i for i in range(self.vocab_size )}
      vocab.update(self.added_tokens_encoder )
      return vocab





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	**__UpperCAmelCase ):

      '''simple docstring'''




      if not self.legacy:
       __UpperCamelCase							    =			SPIECE_UNDERLINE + text.replace(lowerCamelCase_      ,	' ' )
      return super().tokenize(lowerCamelCase_      ,	**lowerCamelCase_ )





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase ):

      '''simple docstring'''




      if not self.legacy:
       __UpperCamelCase							    =			text.startswith(lowerCamelCase_ )
       if is_first:
        __UpperCamelCase							    =			text[1:]

      __UpperCamelCase							    =			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_ ):
       __UpperCamelCase							    =			([tokens[0][1:]] if len(tokens[0] ) > 1 else []) + tokens[1:]
      return tokens





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase ):

      '''simple docstring'''




      return self.sp_model.piece_to_id(lowerCamelCase_ )





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase ):

      '''simple docstring'''




      __UpperCamelCase							    =			self.sp_model.IdToPiece(lowerCamelCase_ )
      return token





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase ):

      '''simple docstring'''




      __UpperCamelCase							    =			[]
      __UpperCamelCase							    =			""""""
      __UpperCamelCase							    =			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
        __UpperCamelCase							    =			True
        __UpperCamelCase							    =			[]
       else:
        current_sub_tokens.append(lowerCamelCase_ )
        __UpperCamelCase							    =			False
      out_string += self.sp_model.decode(lowerCamelCase_ )
      return out_string





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase = None ):

      '''simple docstring'''




      if not os.path.isdir(lowerCamelCase_ ):
       logger.error(F'Vocabulary path ({save_directory}) should be a directory' )
       return
      __UpperCamelCase							    =			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:
        __UpperCamelCase							    =			self.sp_model.serialized_model_proto()
        fi.write(lowerCamelCase_ )

      return (out_vocab_file,)





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase=None ):

      '''simple docstring'''




      __UpperCamelCase							    =			[self.bos_token_id] if self.add_bos_token else []
      __UpperCamelCase							    =			[self.eos_token_id] if self.add_eos_token else []

      __UpperCamelCase							    =			bos_token_id + token_ids_a + eos_token_id

      if token_ids_a is not None:
       __UpperCamelCase							    =			output + bos_token_id + token_ids_a + eos_token_id

      return output





     def 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase = None      ,	__UpperCAmelCase = 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_ )

      __UpperCamelCase							    =			[1] if self.add_bos_token else []
      __UpperCamelCase							    =			[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 		UpperCAmelCase   (      self      ,	__UpperCAmelCase      ,	__UpperCAmelCase = None ):

      '''simple docstring'''




      __UpperCamelCase							    =			[self.bos_token_id] if self.add_bos_token else []
      __UpperCamelCase							    =			[self.eos_token_id] if self.add_eos_token else []

      __UpperCamelCase							    =			[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 		UpperCAmelCase   (      self      ,	__UpperCAmelCase ):

      '''simple docstring'''




      __UpperCamelCase							    =			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...)' )

      __UpperCamelCase							    =			[]
      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]:
        __UpperCamelCase							    =			(
            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]:
       __UpperCamelCase							    =			(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







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


__lowerCamelCase   	=  {'''configuration_visual_bert''': ['''VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''VisualBertConfig''']}

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __lowerCamelCase   	=  [
           '''VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST''',
           '''VisualBertForMultipleChoice''',
           '''VisualBertForPreTraining''',
           '''VisualBertForQuestionAnswering''',
           '''VisualBertForRegionToPhraseAlignment''',
           '''VisualBertForVisualReasoning''',
           '''VisualBertLayer''',
           '''VisualBertModel''',
           '''VisualBertPreTrainedModel''',
       ]


if TYPE_CHECKING:
       from .configuration_visual_bert import VISUAL_BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, VisualBertConfig

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_visual_bert import (
                  VISUAL_BERT_PRETRAINED_MODEL_ARCHIVE_LIST,
                  VisualBertForMultipleChoice,
                  VisualBertForPreTraining,
                  VisualBertForQuestionAnswering,
                  VisualBertForRegionToPhraseAlignment,
                  VisualBertForVisualReasoning,
                  VisualBertLayer,
                  VisualBertModel,
                  VisualBertPreTrainedModel,
              )


else:
       import sys

       __lowerCamelCase   	=  _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



