'''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										= logging.get_logger(__name__)

_A										= {'vocab_file': 'tokenizer.model'}

_A										= {
    '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										= {
    'hf-internal-testing/llama-tokenizer': 2_0_4_8,
}
_A										= '▁'

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

# fmt: off
_A										= '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__	(							_snake_case      ):






   """simple docstring"""
   A				:							Optional[int]			     =     VOCAB_FILES_NAMES
   A				:							Optional[Any]			     =     PRETRAINED_VOCAB_FILES_MAP
   A				:							Tuple			     =     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   A				:							Optional[int]			     =     ['''input_ids''', '''attention_mask''']
   def __init__(self							,					_a							,					_a="<unk>"							,					_a="<s>"							,					_a="</s>"							,					_a=None							,					_a = None							,					_a=True							,					_a=False							,					_a=False							,					_a=True							,					**_a							,					)     ->  List[str]:
        lowercase_       :							str  					=       {} if sp_model_kwargs is None else sp_model_kwargs
        lowercase_       :							int  					=       AddedToken(_a							,					lstrip=_a							,					rstrip=_a					) if isinstance(_a							,					_a					) else bos_token
        lowercase_       :							Optional[Any]  					=       AddedToken(_a							,					lstrip=_a							,					rstrip=_a					) if isinstance(_a							,					_a					) else eos_token
        lowercase_       :							Optional[int]  					=       AddedToken(_a							,					lstrip=_a							,					rstrip=_a					) if isinstance(_a							,					_a					) else unk_token
        lowercase_       :							Any  					=       AddedToken(_a							,					lstrip=_a							,					rstrip=_a					) if isinstance(_a							,					_a					) else pad_token
        super().__init__(
            bos_token=_a							,					eos_token=_a							,					unk_token=_a							,					pad_token=_a							,					add_bos_token=_a							,					add_eos_token=_a							,					sp_model_kwargs=self.sp_model_kwargs							,					clean_up_tokenization_spaces=_a							,					legacy=_a							,					**_a							,					)
        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'					)
        lowercase_       :							Optional[int]  					=       legacy
        lowercase_       :							List[str]  					=       vocab_file
        lowercase_       :							Union[str, Any]  					=       add_bos_token
        lowercase_       :							Tuple  					=       add_eos_token
        lowercase_       :							Optional[Any]  					=       spm.SentencePieceProcessor(**self.sp_model_kwargs					)
        self.sp_model.Load(_a					)
   def __getstate__(self					)     ->  Union[str, Any]:
        lowercase_       :							Optional[int]  					=       self.__dict__.copy()
        lowercase_       :							Optional[Any]  					=       None
        lowercase_       :							List[str]  					=       self.sp_model.serialized_model_proto()
        return state
   def __setstate__(self							,					_a					)     ->  Optional[Any]:
        lowercase_       :							Union[str, Any]  					=       d
        lowercase_       :							Any  					=       spm.SentencePieceProcessor(**self.sp_model_kwargs					)
        self.sp_model.LoadFromSerializedProto(self.sp_model_proto					)
   @property
   def 		_lowerCamelCase			(self					)     ->  Any:
        return self.sp_model.get_piece_size()
   def 		_lowerCamelCase			(self					)     ->  Union[str, Any]:
        lowercase_       :							Dict  					=       {self.convert_ids_to_tokens(_a					): i for i in range(self.vocab_size					)}
        vocab.update(self.added_tokens_encoder					)
        return vocab
   def 		_lowerCamelCase			(self							,					_a							,					**_a					)     ->  List[str]:
        # Replace the SPIECE_UNDERLINE with a space to make sure SPIECE_UNDERLINE is only used at
        # the beginning of the text
        if not self.legacy:
             lowercase_       :							int  					=       SPIECE_UNDERLINE + text.replace(_a							,					' '					)
        return super().tokenize(_a							,					**_a					)
   def 		_lowerCamelCase			(self							,					_a					)     ->  Optional[int]:
        if not self.legacy:
             lowercase_       :							Dict  					=       text.startswith(_a					)
             if is_first:
                  lowercase_       :							Union[str, Any]  					=       text[1:]

        lowercase_       :							List[str]  					=       self.sp_model.encode(_a							,					out_type=_a					)

        if not self.legacy and not is_first and not text.startswith(' '					) and tokens[0].startswith(_a					):
             lowercase_       :							Tuple  					=       ([tokens[0][1:]] if len(tokens[0]					) > 1 else []) + tokens[1:]
        return tokens
   def 		_lowerCamelCase			(self							,					_a					)     ->  str:
        return self.sp_model.piece_to_id(_a					)
   def 		_lowerCamelCase			(self							,					_a					)     ->  Dict:
        lowercase_       :							List[Any]  					=       self.sp_model.IdToPiece(_a					)
        return token
   def 		_lowerCamelCase			(self							,					_a					)     ->  Optional[int]:
        lowercase_       :							Dict  					=       []
        lowercase_       :							str  					=       ''
        lowercase_       :							List[Any]  					=       False
        for i, token in enumerate(_a					):
             # 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(_a					) + token
                  lowercase_       :							List[Any]  					=       True
                  lowercase_       :							List[Any]  					=       []
             else:
                  current_sub_tokens.append(_a					)
                  lowercase_       :							List[Any]  					=       False
        out_string += self.sp_model.decode(_a					)
        return out_string
   def 		_lowerCamelCase			(self							,					_a							,					_a = None					)     ->  Tuple[str]:
        if not os.path.isdir(_a					):
             logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''					)
             return
        lowercase_       :							List[Any]  					=       os.path.join(
            _a							,					(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']					)

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

        return (out_vocab_file,)
   def 		_lowerCamelCase			(self							,					_a							,					_a=None					)     ->  Optional[int]:
        lowercase_       :							Union[str, Any]  					=       [self.bos_token_id] if self.add_bos_token else []
        lowercase_       :							str  					=       [self.eos_token_id] if self.add_eos_token else []

        lowercase_       :							List[Any]  					=       bos_token_id + token_ids_a + eos_token_id

        if token_ids_a is not None:
             lowercase_       :							Optional[Any]  					=       output + bos_token_id + token_ids_a + eos_token_id

        return output
   def 		_lowerCamelCase			(self							,					_a							,					_a = None							,					_a = False					)     ->  List[int]:
        if already_has_special_tokens:
             return super().get_special_tokens_mask(
                 token_ids_a=_a							,					token_ids_a=_a							,					already_has_special_tokens=_a					)

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

        if token_ids_a is None:
             return bos_token_id + ([0] * len(_a					)) + eos_token_id
        return (
            bos_token_id
            + ([0] * len(_a					))
            + eos_token_id
            + bos_token_id
            + ([0] * len(_a					))
            + eos_token_id
        )
   def 		_lowerCamelCase			(self							,					_a							,					_a = None					)     ->  List[int]:
        lowercase_       :							Optional[Any]  					=       [self.bos_token_id] if self.add_bos_token else []
        lowercase_       :							Tuple  					=       [self.eos_token_id] if self.add_eos_token else []

        lowercase_       :							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 		_lowerCamelCase			(self							,					_a					)     ->  List[int]:
        lowercase_       :							int  					=       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...)'					)

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





'''simple docstring'''




import os

from packaging import version

from .. import __version__
from .accelerate_utils import apply_forward_hook
from .constants import (
    CONFIG_NAME,
    DEPRECATED_REVISION_ARGS,
    DIFFUSERS_CACHE,
    DIFFUSERS_DYNAMIC_MODULE_NAME,
    FLAX_WEIGHTS_NAME,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    ONNX_EXTERNAL_WEIGHTS_NAME,
    ONNX_WEIGHTS_NAME,
    SAFETENSORS_WEIGHTS_NAME,
    TEXT_ENCODER_ATTN_MODULE,
    WEIGHTS_NAME,
)
from .deprecation_utils import deprecate
from .doc_utils import replace_example_docstring
from .dynamic_modules_utils import get_class_from_dynamic_module
from .hub_utils import (
    HF_HUB_OFFLINE,
    _add_variant,
    _get_model_file,
    extract_commit_hash,
    http_user_agent,
)
from .import_utils import (
    BACKENDS_MAPPING,
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    is_accelerate_available,
    is_accelerate_version,
    is_bsa_available,
    is_flax_available,
    is_ftfy_available,
    is_inflect_available,
    is_invisible_watermark_available,
    is_k_diffusion_available,
    is_k_diffusion_version,
    is_librosa_available,
    is_note_seq_available,
    is_omegaconf_available,
    is_onnx_available,
    is_safetensors_available,
    is_scipy_available,
    is_tensorboard_available,
    is_tf_available,
    is_torch_available,
    is_torch_version,
    is_torchsde_available,
    is_transformers_available,
    is_transformers_version,
    is_unidecode_available,
    is_wandb_available,
    is_xformers_available,
    requires_backends,
)
from .logging import get_logger
from .outputs import BaseOutput
from .pil_utils import PIL_INTERPOLATION, numpy_to_pil, pt_to_pil
from .torch_utils import is_compiled_module, randn_tensor


if is_torch_available():
 from .testing_utils import (
     floats_tensor,
     load_hf_numpy,
     load_image,
     load_numpy,
     load_pt,
     nightly,
     parse_flag_from_env,
     print_tensor_test,
     require_torch_a,
     require_torch_gpu,
     skip_mps,
     slow,
     torch_all_close,
     torch_device,
 )
 from .torch_utils import maybe_allow_in_graph

from .testing_utils import export_to_gif, export_to_video


_A										= get_logger(__name__)

def _UpperCamelCase (							SCREAMING_SNAKE_CASE_				):
     if version.parse(SCREAMING_SNAKE_CASE_				) < version.parse(SCREAMING_SNAKE_CASE_				):
          if "dev" in min_version:
               lowercase_       :							Tuple  					=       (
                   'This example requires a source install from HuggingFace diffusers (see '
                   '`https://huggingface.co/docs/diffusers/installation#install-from-source`),'
               )
          else:
               lowercase_       :							List[Any]  					=       f'''This example requires a minimum version of {min_version},'''
          error_message += f''' but the version found is {__version__}.\n'''
          raise ImportError(SCREAMING_SNAKE_CASE_				)




