'''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": 2048,
}
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 		SCREAMING_SNAKE_CASE_					(_UpperCAmelCase      ):



			"""simple docstring"""






			__magic_name__ :				List[Any]   							=       VOCAB_FILES_NAMES
			__magic_name__ :				Tuple   							=       PRETRAINED_VOCAB_FILES_MAP
			__magic_name__ :				Optional[int]   							=       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
			__magic_name__ :				List[str]   							=       ["""input_ids""", """attention_mask"""]



			def __init__(							self				,			snake_case_				,			snake_case_="<unk>"				,			snake_case_="<s>"				,			snake_case_="</s>"				,			snake_case_=None				,			snake_case_ = None				,			snake_case_=True				,			snake_case_=False				,			snake_case_=False				,			snake_case_=True				,			**snake_case_				,			):
									snake_case :       Optional[Any]				=    {} if sp_model_kwargs is None else sp_model_kwargs
									snake_case :       Dict				=    AddedToken(snake_case_				,			lstrip=snake_case_				,			rstrip=snake_case_					) if isinstance(snake_case_				,			snake_case_					) else bos_token
									snake_case :       Optional[int]				=    AddedToken(snake_case_				,			lstrip=snake_case_				,			rstrip=snake_case_					) if isinstance(snake_case_				,			snake_case_					) else eos_token
									snake_case :       Union[str, Any]				=    AddedToken(snake_case_				,			lstrip=snake_case_				,			rstrip=snake_case_					) if isinstance(snake_case_				,			snake_case_					) else unk_token
									snake_case :       List[str]				=    AddedToken(snake_case_				,			lstrip=snake_case_				,			rstrip=snake_case_					) if isinstance(snake_case_				,			snake_case_					) else pad_token
									super().__init__(
									    bos_token=snake_case_				,			eos_token=snake_case_				,			unk_token=snake_case_				,			pad_token=snake_case_				,			add_bos_token=snake_case_				,			add_eos_token=snake_case_				,			sp_model_kwargs=self.sp_model_kwargs				,			clean_up_tokenization_spaces=snake_case_				,			legacy=snake_case_				,			**snake_case_				,			)
									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"					)
									snake_case :       List[Any]				=    legacy
									snake_case :       Optional[int]				=    vocab_file
									snake_case :       List[Any]				=    add_bos_token
									snake_case :       Any				=    add_eos_token
									snake_case :       str				=    spm.SentencePieceProcessor(**self.sp_model_kwargs					)
									self.sp_model.Load(snake_case_					)



			def __getstate__(							self					):
									snake_case :       str				=    self.__dict__.copy()
									snake_case :       Optional[int]				=    None
									snake_case :       Optional[int]				=    self.sp_model.serialized_model_proto()
									return state



			def __setstate__(							self				,			snake_case_					):
									snake_case :       str				=    d
									snake_case :       int				=    spm.SentencePieceProcessor(**self.sp_model_kwargs					)
									self.sp_model.LoadFromSerializedProto(self.sp_model_proto					)



			@property
			def   lowerCamelCase (							self					):
									return self.sp_model.get_piece_size()



			def   lowerCamelCase (							self					):
									snake_case :       Tuple				=    {self.convert_ids_to_tokens(snake_case_					): i for i in range(self.vocab_size					)}
									vocab.update(self.added_tokens_encoder					)
									return vocab



			def   lowerCamelCase (							self				,			snake_case_				,			**snake_case_					):
									# 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:
															snake_case :       List[Any]				=    SPIECE_UNDERLINE + text.replace(snake_case_				,			" "					)
									return super().tokenize(snake_case_				,			**snake_case_					)



			def   lowerCamelCase (							self				,			snake_case_					):
									if not self.legacy:
															snake_case :       Union[str, Any]				=    text.startswith(snake_case_					)
															if is_first:
																					snake_case :       Optional[Any]				=    text[1:]

									snake_case :       int				=    self.sp_model.encode(snake_case_				,			out_type=snake_case_					)

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



			def   lowerCamelCase (							self				,			snake_case_					):
									return self.sp_model.piece_to_id(snake_case_					)



			def   lowerCamelCase (							self				,			snake_case_					):
									snake_case :       Optional[Any]				=    self.sp_model.IdToPiece(snake_case_					)
									return token



			def   lowerCamelCase (							self				,			snake_case_					):
									snake_case :       List[Any]				=    []
									snake_case :       Optional[Any]				=    ""
									snake_case :       Dict				=    False
									for i, token in enumerate(snake_case_					):
															# 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(snake_case_					) + token
																					snake_case :       Union[str, Any]				=    True
																					snake_case :       int				=    []
															else:
																					current_sub_tokens.append(snake_case_					)
																					snake_case :       Optional[Any]				=    False
									out_string += self.sp_model.decode(snake_case_					)
									return out_string



			def   lowerCamelCase (							self				,			snake_case_				,			snake_case_ = None					):
									if not os.path.isdir(snake_case_					):
															logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""					)
															return
									snake_case :       Optional[Any]				=    os.path.join(
									    snake_case_				,			(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]					)

									if os.path.abspath(self.vocab_file					) != os.path.abspath(snake_case_					) and os.path.isfile(self.vocab_file					):
															copyfile(self.vocab_file				,			snake_case_					)
									elif not os.path.isfile(self.vocab_file					):
															with open(snake_case_				,			"wb"					) as fi:
																					snake_case :       Optional[Any]				=    self.sp_model.serialized_model_proto()
																					fi.write(snake_case_					)

									return (out_vocab_file,)



			def   lowerCamelCase (							self				,			snake_case_				,			snake_case_=None					):
									snake_case :       Optional[Any]				=    [self.bos_token_id] if self.add_bos_token else []
									snake_case :       List[str]				=    [self.eos_token_id] if self.add_eos_token else []

									snake_case :       List[str]				=    bos_token_id + token_ids_a + eos_token_id

									if token_ids_a is not None:
															snake_case :       Any				=    output + bos_token_id + token_ids_a + eos_token_id

									return output



			def   lowerCamelCase (							self				,			snake_case_				,			snake_case_ = None				,			snake_case_ = False					):
									if already_has_special_tokens:
															return super().get_special_tokens_mask(
															    token_ids_a=snake_case_				,			token_ids_a=snake_case_				,			already_has_special_tokens=snake_case_					)

									snake_case :       Any				=    [1] if self.add_bos_token else []
									snake_case :       Optional[Any]				=    [1] if self.add_eos_token else []

									if token_ids_a is None:
															return bos_token_id + ([0] * len(snake_case_					)) + eos_token_id
									return (
									    bos_token_id
									    + ([0] * len(snake_case_					))
									    + eos_token_id
									    + bos_token_id
									    + ([0] * len(snake_case_					))
									    + eos_token_id
									)



			def   lowerCamelCase (							self				,			snake_case_				,			snake_case_ = None					):
									snake_case :       Optional[int]				=    [self.bos_token_id] if self.add_bos_token else []
									snake_case :       Optional[int]				=    [self.eos_token_id] if self.add_eos_token else []

									snake_case :       Optional[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				,			snake_case_					):
									snake_case :       Tuple				=    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 :       List[int]				=    []
									if len(conversation.past_user_inputs					) > 0:
															if not conversation.past_user_inputs[0].startswith(snake_case_					) or E_SYS not in conversation.past_user_inputs[0]:
																					snake_case :       Dict				=    (
																					    B_SYS + DEFAULT_SYSTEM_PROMPT + E_SYS + conversation.past_user_inputs[0]
																					)
									elif not dialogue[0][1].startswith(snake_case_					) or E_SYS not in dialogue[0][1]:
															snake_case :       Union[str, Any]				=    (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=snake_case_					)
									        + [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=snake_case_					)
									return dialog_tokens






'''simple docstring'''

import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding




class 		SCREAMING_SNAKE_CASE_					(_UpperCAmelCase      ):



			"""simple docstring"""






			__magic_name__ :				Tuple   							=       ["""image_processor""", """tokenizer"""]
			__magic_name__ :				List[str]   							=       """AutoImageProcessor"""
			__magic_name__ :				List[str]   							=       """AutoTokenizer"""



			def __init__(							self				,			snake_case_=None				,			snake_case_=None				,			**snake_case_					):
									snake_case :       Any				=    None
									if "feature_extractor" in kwargs:
															warnings.warn(
															    "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
															    " instead."				,			snake_case_				,			)
															snake_case :       str				=    kwargs.pop("feature_extractor"					)

									snake_case :       Optional[int]				=    image_processor if image_processor is not None else feature_extractor
									if image_processor is None:
															raise ValueError("You have to specify an image_processor."					)
									if tokenizer is None:
															raise ValueError("You have to specify a tokenizer."					)

									super().__init__(snake_case_				,			snake_case_					)
									snake_case :       Optional[int]				=    self.image_processor



			def __call__(							self				,			snake_case_=None				,			snake_case_=None				,			snake_case_=None				,			**snake_case_					):

									if text is None and images is None:
															raise ValueError("You have to specify either text or images. Both cannot be none."					)

									if text is not None:
															snake_case :       Optional[int]				=    self.tokenizer(snake_case_				,			return_tensors=snake_case_				,			**snake_case_					)

									if images is not None:
															snake_case :       List[Any]				=    self.image_processor(snake_case_				,			return_tensors=snake_case_				,			**snake_case_					)

									if text is not None and images is not None:
															snake_case :       str				=    image_features.pixel_values
															return encoding
									elif text is not None:
															return encoding
									else:
															return BatchEncoding(data=dict(**snake_case_					)				,			tensor_type=snake_case_					)



			def   lowerCamelCase (							self				,			*snake_case_				,			**snake_case_					):
									return self.tokenizer.batch_decode(*snake_case_				,			**snake_case_					)



			def   lowerCamelCase (							self				,			*snake_case_				,			**snake_case_					):
									return self.tokenizer.decode(*snake_case_				,			**snake_case_					)



			@property
			def   lowerCamelCase (							self					):
									snake_case :       List[str]				=    self.tokenizer.model_input_names
									snake_case :       Any				=    self.image_processor.model_input_names
									return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names					)					)



			@property
			def   lowerCamelCase (							self					):
									warnings.warn(
									    "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."				,			snake_case_				,			)
									return self.image_processor_class






			@property
			def   lowerCamelCase (							self					):
									warnings.warn(
									    "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."				,			snake_case_				,			)
									return self.image_processor





