






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

lowerCamelCase_					:			Dict     						=				logging.get_logger(__name__)

lowerCamelCase_					:			Union[str, Any]     						=				{'''vocab_file''': '''tokenizer.model'''}

lowerCamelCase_					:			Optional[int]     						=				{
    '''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''',
    },
}
lowerCamelCase_					:			List[str]     						=				{
    '''hf-internal-testing/llama-tokenizer''': 2048,
}
lowerCamelCase_					:			Optional[Any]     						=				'''▁'''

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

# fmt: off
lowerCamelCase_					:			List[str]     						=				'''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  _SCREAMING_SNAKE_CASE				(		SCREAMING_SNAKE_CASE						):


			'''simple docstring'''





			__a				:				Dict         =       VOCAB_FILES_NAMES
			__a				:				Tuple         =       PRETRAINED_VOCAB_FILES_MAP
			__a				:				List[Any]         =       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			__a				:				Optional[Any]         =       ["input_ids", "attention_mask"]






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

									'''simple docstring'''







									UpperCamelCase__       =			{} if sp_model_kwargs is None else sp_model_kwargs
									UpperCamelCase__       =			AddedToken(lowercase			,   lstrip=lowercase			,   rstrip=lowercase      ) if isinstance(lowercase			,   lowercase      ) else bos_token
									UpperCamelCase__       =			AddedToken(lowercase			,   lstrip=lowercase			,   rstrip=lowercase      ) if isinstance(lowercase			,   lowercase      ) else eos_token
									UpperCamelCase__       =			AddedToken(lowercase			,   lstrip=lowercase			,   rstrip=lowercase      ) if isinstance(lowercase			,   lowercase      ) else unk_token
									UpperCamelCase__       =			AddedToken(lowercase			,   lstrip=lowercase			,   rstrip=lowercase      ) if isinstance(lowercase			,   lowercase      ) else pad_token
									super().__init__(
									    bos_token=lowercase			,   eos_token=lowercase			,   unk_token=lowercase			,   pad_token=lowercase			,   add_bos_token=lowercase			,   add_eos_token=lowercase			,   sp_model_kwargs=self.sp_model_kwargs			,   clean_up_tokenization_spaces=lowercase			,   legacy=lowercase			,   **lowercase			,   )
									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(lowercase      )






			def __getstate__( self				:    List[str]      )				->     Dict:

									'''simple docstring'''







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






			def __setstate__( self				:    int			,   lowercase				:    int      )				->     Any:

									'''simple docstring'''







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






			@property
			def 					A   ( self				:    Tuple      )				->     Optional[Any]:

									'''simple docstring'''







									return self.sp_model.get_piece_size()






			def 					A   ( self				:    Union[str, Any]      )				->     Tuple:

									'''simple docstring'''







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






			def 					A   ( self				:    Optional[int]			,   lowercase				:    str			,   **lowercase				:    List[Any]      )				->     List[str]:

									'''simple docstring'''







									if not self.legacy:
															UpperCamelCase__       =			SPIECE_UNDERLINE + text.replace(lowercase			,   """ """      )
									return super().tokenize(lowercase			,   **lowercase      )






			def 					A   ( self				:    Any			,   lowercase				:    Optional[Any]      )				->     Union[str, Any]:

									'''simple docstring'''







									if not self.legacy:
															UpperCamelCase__       =			text.startswith(lowercase      )
															if is_first:
																					UpperCamelCase__       =			text[1:]

									UpperCamelCase__       =			self.sp_model.encode(lowercase			,   out_type=lowercase      )

									if not self.legacy and not is_first and not text.startswith(""" """      ) and tokens[0].startswith(lowercase      ):
															UpperCamelCase__       =			([tokens[0][1:]] if len(tokens[0]      ) > 1 else []) + tokens[1:]
									return tokens






			def 					A   ( self				:    List[Any]			,   lowercase				:    str      )				->     Any:

									'''simple docstring'''







									return self.sp_model.piece_to_id(lowercase      )






			def 					A   ( self				:    Any			,   lowercase				:    Dict      )				->     Any:

									'''simple docstring'''







									UpperCamelCase__       =			self.sp_model.IdToPiece(lowercase      )
									return token






			def 					A   ( self				:    int			,   lowercase				:    List[Any]      )				->     Dict:

									'''simple docstring'''







									UpperCamelCase__       =			[]
									UpperCamelCase__       =			""""""
									UpperCamelCase__       =			False
									for i, token in enumerate(lowercase      ):
															# 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(lowercase      ) + token
																					UpperCamelCase__       =			True
																					UpperCamelCase__       =			[]
															else:
																					current_sub_tokens.append(lowercase      )
																					UpperCamelCase__       =			False
									out_string += self.sp_model.decode(lowercase      )
									return out_string






			def 					A   ( self				:    Tuple			,   lowercase				:    List[Any]			,   lowercase				:    Optional[str] = None      )				->     Tuple[str]:

									'''simple docstring'''







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

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

									return (out_vocab_file,)






			def 					A   ( self				:    Dict			,   lowercase				:    Optional[int]			,   lowercase				:    Optional[int]=None      )				->     str:

									'''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 					A   ( self				:    int			,   lowercase				:    List[int]			,   lowercase				:    Optional[List[int]] = None			,   lowercase				:    bool = False      )				->     List[int]:

									'''simple docstring'''







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

									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(lowercase      )) + eos_token_id
									return (
									    bos_token_id
									    + ([0] * len(lowercase      ))
									    + eos_token_id
									    + bos_token_id
									    + ([0] * len(lowercase      ))
									    + eos_token_id
									)






			def 					A   ( self				:    str			,   lowercase				:    List[int]			,   lowercase				:    Optional[List[int]] = None      )				->     List[int]:

									'''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 					A   ( self				:    Dict			,   lowercase				:    "Conversation"      )				->     List[int]:

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








'''simple docstring'''


from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import BaseOutput, is_torch_available, is_transformers_available
@dataclass
# Copied from diffusers.pipelines.stable_diffusion.__init__.StableDiffusionPipelineOutput with Stable->Alt
class  _SCREAMING_SNAKE_CASE				(		SCREAMING_SNAKE_CASE						):


			'''simple docstring'''





			__a				:				Union[List[PIL.Image.Image], np.ndarray]
			__a				:				Optional[List[bool]]


if is_transformers_available() and is_torch_available():
					from .modeling_roberta_series import RobertaSeriesModelWithTransformation
					from .pipeline_alt_diffusion import AltDiffusionPipeline
					from .pipeline_alt_diffusion_imgaimg import AltDiffusionImgaImgPipeline
