

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:
    lowerCamelCase_    =					None

lowerCamelCase_    =					logging.get_logger(__name__)
lowerCamelCase_    =					{'''vocab_file''': '''tokenizer.model''', '''tokenizer_file''': '''tokenizer.json'''}

lowerCamelCase_   ,  lowerCamelCase_    =					'''[INST]''', '''[/INST]'''
lowerCamelCase_   ,  lowerCamelCase_    =					'''<<SYS>>\n''', '''\n<</SYS>>\n\n'''

# fmt: off
lowerCamelCase_    =					'''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  __lowerCamelCase				(	__snake_case	):
      lowerCamelCase_	:      Any          =					VOCAB_FILES_NAMES
      lowerCamelCase_	:      Tuple          =					LlamaTokenizer
      lowerCamelCase_	:      Optional[int]          =					'left'
      lowerCamelCase_	:      Optional[Any]          =					['input_ids', 'attention_mask']







      def __init__(     self							,  lowerCamelCase=None							,  lowerCamelCase=None							,  lowerCamelCase=False							,  lowerCamelCase="<unk>"							,  lowerCamelCase="<s>"							,  lowerCamelCase="</s>"							,  lowerCamelCase=True							,  lowerCamelCase=False							,  **lowerCamelCase							,  )						->       Dict:
        super().__init__(
            vocab_file=lowerCamelCase							,  tokenizer_file=lowerCamelCase							,  clean_up_tokenization_spaces=lowerCamelCase							,  unk_token=lowerCamelCase							,  bos_token=lowerCamelCase							,  eos_token=lowerCamelCase							,  **lowerCamelCase							,  )
        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 	lowerCAmelCase_    (     self   )						->       Tuple:
        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=lowerCamelCase							,  pair=lowerCamelCase							,  special_tokens=lowerCamelCase   )







      @property
      def 	lowerCAmelCase_    (     self   )						->       Dict:
        return self._add_eos_token







      @property
      def 	lowerCAmelCase_    (     self   )						->       int:
        return self._add_bos_token







      @add_eos_token.setter
      def 	lowerCAmelCase_    (     self							,  lowerCamelCase   )						->       Dict:
        snake_case_       						=      value
        self.update_post_processor()







      @add_bos_token.setter
      def 	lowerCAmelCase_    (     self							,  lowerCamelCase   )						->       Any:
        snake_case_       						=      value
        self.update_post_processor()







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase = None   )						->       Tuple[str]:
        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(lowerCamelCase   ):
          logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''   )
          return
        snake_case_       						=      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   ):
          copyfile(self.vocab_file							,  lowerCamelCase   )

        return (out_vocab_file,)







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase   )						->       Optional[Any]:
        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(lowerCamelCase   ) 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(lowerCamelCase   ) 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=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




"""simple docstring"""







from typing import TYPE_CHECKING

from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available


UpperCAmelCase:   int       			=							{
    """configuration_utils""": ["""GenerationConfig"""],
    """streamers""": ["""TextIteratorStreamer""", """TextStreamer"""],
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCAmelCase:   List[Any]       			=							[
		    """Constraint""",
		    """ConstraintListState""",
		    """DisjunctiveConstraint""",
		    """PhrasalConstraint""",
		]
		UpperCAmelCase:   Optional[Any]       			=							[
		    """BeamHypotheses""",
		    """BeamScorer""",
		    """BeamSearchScorer""",
		    """ConstrainedBeamSearchScorer""",
		]
		UpperCAmelCase:   Any       			=							[
		    """EpsilonLogitsWarper""",
		    """EtaLogitsWarper""",
		    """ForcedBOSTokenLogitsProcessor""",
		    """ForcedEOSTokenLogitsProcessor""",
		    """HammingDiversityLogitsProcessor""",
		    """InfNanRemoveLogitsProcessor""",
		    """LogitsProcessor""",
		    """LogitsProcessorList""",
		    """LogitsWarper""",
		    """MinLengthLogitsProcessor""",
		    """MinNewTokensLengthLogitsProcessor""",
		    """NoBadWordsLogitsProcessor""",
		    """NoRepeatNGramLogitsProcessor""",
		    """PrefixConstrainedLogitsProcessor""",
		    """RepetitionPenaltyLogitsProcessor""",
		    """SequenceBiasLogitsProcessor""",
		    """EncoderRepetitionPenaltyLogitsProcessor""",
		    """TemperatureLogitsWarper""",
		    """TopKLogitsWarper""",
		    """TopPLogitsWarper""",
		    """TypicalLogitsWarper""",
		    """EncoderNoRepeatNGramLogitsProcessor""",
		    """ExponentialDecayLengthPenalty""",
		    """LogitNormalization""",
		]
		UpperCAmelCase:   str       			=							[
		    """MaxNewTokensCriteria""",
		    """MaxLengthCriteria""",
		    """MaxTimeCriteria""",
		    """StoppingCriteria""",
		    """StoppingCriteriaList""",
		    """validate_stopping_criteria""",
		]
		UpperCAmelCase:   Optional[Any]       			=							[
		    """GenerationMixin""",
		    """top_k_top_p_filtering""",
		    """GreedySearchEncoderDecoderOutput""",
		    """GreedySearchDecoderOnlyOutput""",
		    """SampleEncoderDecoderOutput""",
		    """SampleDecoderOnlyOutput""",
		    """BeamSearchEncoderDecoderOutput""",
		    """BeamSearchDecoderOnlyOutput""",
		    """BeamSampleEncoderDecoderOutput""",
		    """BeamSampleDecoderOnlyOutput""",
		    """ContrastiveSearchEncoderDecoderOutput""",
		    """ContrastiveSearchDecoderOnlyOutput""",
		]

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCAmelCase:   Any       			=							[
		    """TFForcedBOSTokenLogitsProcessor""",
		    """TFForcedEOSTokenLogitsProcessor""",
		    """TFLogitsProcessor""",
		    """TFLogitsProcessorList""",
		    """TFLogitsWarper""",
		    """TFMinLengthLogitsProcessor""",
		    """TFNoBadWordsLogitsProcessor""",
		    """TFNoRepeatNGramLogitsProcessor""",
		    """TFRepetitionPenaltyLogitsProcessor""",
		    """TFTemperatureLogitsWarper""",
		    """TFTopKLogitsWarper""",
		    """TFTopPLogitsWarper""",
		    """TFForceTokensLogitsProcessor""",
		    """TFSuppressTokensAtBeginLogitsProcessor""",
		    """TFSuppressTokensLogitsProcessor""",
		]
		UpperCAmelCase:   Tuple       			=							[
		    """TFGenerationMixin""",
		    """tf_top_k_top_p_filtering""",
		    """TFGreedySearchDecoderOnlyOutput""",
		    """TFGreedySearchEncoderDecoderOutput""",
		    """TFSampleEncoderDecoderOutput""",
		    """TFSampleDecoderOnlyOutput""",
		    """TFBeamSearchEncoderDecoderOutput""",
		    """TFBeamSearchDecoderOnlyOutput""",
		    """TFBeamSampleEncoderDecoderOutput""",
		    """TFBeamSampleDecoderOnlyOutput""",
		    """TFContrastiveSearchEncoderDecoderOutput""",
		    """TFContrastiveSearchDecoderOnlyOutput""",
		]

try:
		if not is_flax_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		UpperCAmelCase:   Tuple       			=							[
		    """FlaxForcedBOSTokenLogitsProcessor""",
		    """FlaxForcedEOSTokenLogitsProcessor""",
		    """FlaxLogitsProcessor""",
		    """FlaxLogitsProcessorList""",
		    """FlaxLogitsWarper""",
		    """FlaxMinLengthLogitsProcessor""",
		    """FlaxTemperatureLogitsWarper""",
		    """FlaxTopKLogitsWarper""",
		    """FlaxTopPLogitsWarper""",
		]
		UpperCAmelCase:   int       			=							[
		    """FlaxGenerationMixin""",
		    """FlaxGreedySearchOutput""",
		    """FlaxSampleOutput""",
		    """FlaxBeamSearchOutput""",
		]

if TYPE_CHECKING:
		from .configuration_utils import GenerationConfig
		from .streamers import TextIteratorStreamer, TextStreamer

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .beam_constraints import Constraint, ConstraintListState, DisjunctiveConstraint, PhrasalConstraint
				from .beam_search import BeamHypotheses, BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
				from .logits_process import (
				    EncoderNoRepeatNGramLogitsProcessor,
				    EncoderRepetitionPenaltyLogitsProcessor,
				    EpsilonLogitsWarper,
				    EtaLogitsWarper,
				    ExponentialDecayLengthPenalty,
				    ForcedBOSTokenLogitsProcessor,
				    ForcedEOSTokenLogitsProcessor,
				    HammingDiversityLogitsProcessor,
				    InfNanRemoveLogitsProcessor,
				    LogitNormalization,
				    LogitsProcessor,
				    LogitsProcessorList,
				    LogitsWarper,
				    MinLengthLogitsProcessor,
				    MinNewTokensLengthLogitsProcessor,
				    NoBadWordsLogitsProcessor,
				    NoRepeatNGramLogitsProcessor,
				    PrefixConstrainedLogitsProcessor,
				    RepetitionPenaltyLogitsProcessor,
				    SequenceBiasLogitsProcessor,
				    TemperatureLogitsWarper,
				    TopKLogitsWarper,
				    TopPLogitsWarper,
				    TypicalLogitsWarper,
				)
				from .stopping_criteria import (
				    MaxLengthCriteria,
				    MaxNewTokensCriteria,
				    MaxTimeCriteria,
				    StoppingCriteria,
				    StoppingCriteriaList,
				    validate_stopping_criteria,
				)
				from .utils import (
				    BeamSampleDecoderOnlyOutput,
				    BeamSampleEncoderDecoderOutput,
				    BeamSearchDecoderOnlyOutput,
				    BeamSearchEncoderDecoderOutput,
				    ContrastiveSearchDecoderOnlyOutput,
				    ContrastiveSearchEncoderDecoderOutput,
				    GenerationMixin,
				    GreedySearchDecoderOnlyOutput,
				    GreedySearchEncoderDecoderOutput,
				    SampleDecoderOnlyOutput,
				    SampleEncoderDecoderOutput,
				    top_k_top_p_filtering,
				)

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .tf_logits_process import (
				    TFForcedBOSTokenLogitsProcessor,
				    TFForcedEOSTokenLogitsProcessor,
				    TFForceTokensLogitsProcessor,
				    TFLogitsProcessor,
				    TFLogitsProcessorList,
				    TFLogitsWarper,
				    TFMinLengthLogitsProcessor,
				    TFNoBadWordsLogitsProcessor,
				    TFNoRepeatNGramLogitsProcessor,
				    TFRepetitionPenaltyLogitsProcessor,
				    TFSuppressTokensAtBeginLogitsProcessor,
				    TFSuppressTokensLogitsProcessor,
				    TFTemperatureLogitsWarper,
				    TFTopKLogitsWarper,
				    TFTopPLogitsWarper,
				)
				from .tf_utils import (
				    TFBeamSampleDecoderOnlyOutput,
				    TFBeamSampleEncoderDecoderOutput,
				    TFBeamSearchDecoderOnlyOutput,
				    TFBeamSearchEncoderDecoderOutput,
				    TFContrastiveSearchDecoderOnlyOutput,
				    TFContrastiveSearchEncoderDecoderOutput,
				    TFGenerationMixin,
				    TFGreedySearchDecoderOnlyOutput,
				    TFGreedySearchEncoderDecoderOutput,
				    TFSampleDecoderOnlyOutput,
				    TFSampleEncoderDecoderOutput,
				    tf_top_k_top_p_filtering,
				)

		try:
				if not is_flax_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .flax_logits_process import (
				    FlaxForcedBOSTokenLogitsProcessor,
				    FlaxForcedEOSTokenLogitsProcessor,
				    FlaxLogitsProcessor,
				    FlaxLogitsProcessorList,
				    FlaxLogitsWarper,
				    FlaxMinLengthLogitsProcessor,
				    FlaxTemperatureLogitsWarper,
				    FlaxTopKLogitsWarper,
				    FlaxTopPLogitsWarper,
				)
				from .flax_utils import FlaxBeamSearchOutput, FlaxGenerationMixin, FlaxGreedySearchOutput, FlaxSampleOutput
else:
		import sys

		UpperCAmelCase:   Optional[Any]       			=							_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



