





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:
				UpperCamelCase__ :			Optional[int]       	=			None

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

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

# fmt: off
UpperCamelCase__ :			List[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 	_UpperCamelCase	(							SCREAMING_SNAKE_CASE_	):







					'''simple docstring'''

					lowerCamelCase  :  List[str]           =							VOCAB_FILES_NAMES
					lowerCamelCase  :  Dict           =							LlamaTokenizer
					lowerCamelCase  :  List[str]           =							"""left"""
					lowerCamelCase  :  Any           =							["""input_ids""", """attention_mask"""]





					def __init__(    self     :	Union[str, Any]			,       __lowercase     :	str=None			,       __lowercase     :	Tuple=None			,       __lowercase     :	str=False			,       __lowercase     :	Any="<unk>"			,       __lowercase     :	Union[str, Any]="<s>"			,       __lowercase     :	int="</s>"			,       __lowercase     :	Tuple=True			,       __lowercase     :	Dict=False			,       **__lowercase     :	str			,       ):






						'''simple docstring'''







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

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





					def 							SCREAMING_SNAKE_CASE				(    self     :	Union[str, Any]		):






						'''simple docstring'''







						UpperCAmelCase_		    =  self.bos_token
						UpperCAmelCase_		    =  self.bos_token_id

						UpperCAmelCase_		    =  self.eos_token
						UpperCAmelCase_		    =  self.eos_token_id

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

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





					@property
					def 							SCREAMING_SNAKE_CASE				(    self     :	str		):






						'''simple docstring'''







						return self._add_eos_token





					@property
					def 							SCREAMING_SNAKE_CASE				(    self     :	Tuple		):






						'''simple docstring'''







						return self._add_bos_token





					@add_eos_token.setter
					def 							SCREAMING_SNAKE_CASE				(    self     :	Optional[int]			,       __lowercase     :	List[Any]		):






						'''simple docstring'''







						UpperCAmelCase_		    =  value
						self.update_post_processor()





					@add_bos_token.setter
					def 							SCREAMING_SNAKE_CASE				(    self     :	Tuple			,       __lowercase     :	Optional[Any]		):






						'''simple docstring'''







						UpperCAmelCase_		    =  value
						self.update_post_processor()





					def 							SCREAMING_SNAKE_CASE				(    self     :	Dict			,       __lowercase     :	Optional[Any]			,       __lowercase     :	str = 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(__UpperCAmelCase		):
							logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""		)
							return
						UpperCAmelCase_		    =  os.path.join(
						    __UpperCAmelCase			,       (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]		)

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

						return (out_vocab_file,)





					def 							SCREAMING_SNAKE_CASE				(    self     :	Optional[Any]			,       __lowercase     :	Optional[Any]		):






						'''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(__UpperCAmelCase		) 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(__UpperCAmelCase		) 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=__UpperCAmelCase		)
						        + [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=__UpperCAmelCase		)
						return dialog_tokens




"""simple docstring"""






import copy

from transformers.configuration_utils import PretrainedConfig
from transformers.utils import logging


UpperCamelCase_						   =   logging.get_logger(__name__)





class 							snake_case       (     SCREAMING_SNAKE_CASE_		):
   a_					:		Tuple     					=     """hybrid-clip"""
   a_					:		Optional[Any]     					=     True







   def __init__( self       ,							__UpperCAmelCase=5_12       ,							**__UpperCAmelCase)   ->Dict:
      super().__init__(**__UpperCAmelCase)

      if "text_config" not in kwargs:
         raise ValueError("`text_config` can not be `None`.")

      if "vision_config" not in kwargs:
         raise ValueError("`vision_config` can not be `None`.")

      a_						   =     kwargs.pop("text_config")
      a_						   =     kwargs.pop("vision_config")

      a_						   =     text_config.pop("model_type")
      a_						   =     vision_config.pop("model_type")

      from transformers import AutoConfig

      a_						   =     AutoConfig.for_model(__UpperCAmelCase       ,							**__UpperCAmelCase)

      if vision_model_type == "clip":
         a_						   =     AutoConfig.for_model(__UpperCAmelCase       ,							**__UpperCAmelCase).vision_config
      elif vision_model_type == "clip_vision_model":
         from transformers import CLIPVisionConfig

         a_						   =     CLIPVisionConfig(**__UpperCAmelCase)
      else:
         a_						   =     AutoConfig.for_model(__UpperCAmelCase       ,							**__UpperCAmelCase)

      a_						   =     projection_dim
      a_						   =     1.0







   @classmethod
   def    UpperCAmelCase__	( cls       ,							__UpperCAmelCase       ,							__UpperCAmelCase       ,							**__UpperCAmelCase)   ->Optional[int]:
      return cls(text_config=text_config.to_dict()       ,							vision_config=vision_config.to_dict()       ,							**__UpperCAmelCase)







   def    UpperCAmelCase__	( self)   ->str:
      a_						   =     copy.deepcopy(self.__dict__)
      a_						   =     self.text_config.to_dict()
      a_						   =     self.vision_config.to_dict()
      a_						   =     self.__class__.model_type
      return output