



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

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

A__       =			'[INST]', '[/INST]'
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    __lowerCAmelCase					(	__UpperCAmelCase			):
				__lowerCamelCase					=							VOCAB_FILES_NAMES
				__lowerCamelCase					=							LlamaTokenizer
				__lowerCamelCase					=							"""left"""
				__lowerCamelCase					=							["""input_ids""", """attention_mask"""]




				def __init__(				self		,							_snake_case=None		,							_snake_case=None		,							_snake_case=False		,							_snake_case="<unk>"		,							_snake_case="<s>"		,							_snake_case="</s>"		,							_snake_case=True		,							_snake_case=False		,							**_snake_case		,							):



									"""simple docstring"""





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

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




				def 				snake_case  (				self						):



									"""simple docstring"""





									_lowerCAmelCase         =       self.bos_token
									_lowerCAmelCase         =       self.bos_token_id

									_lowerCAmelCase         =       self.eos_token
									_lowerCAmelCase         =       self.eos_token_id

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

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




				@property
				def 				snake_case  (				self						):



									"""simple docstring"""





									return self._add_eos_token




				@property
				def 				snake_case  (				self						):



									"""simple docstring"""





									return self._add_bos_token




				@add_eos_token.setter
				def 				snake_case  (				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       value
									self.update_post_processor()




				@add_bos_token.setter
				def 				snake_case  (				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       value
									self.update_post_processor()




				def 				snake_case  (				self		,							_snake_case		,							_snake_case = 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(_lowerCamelCase						):
														logger.error(F'Vocabulary path ({save_directory}) should be a directory'						)
														return
									_lowerCAmelCase         =       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 				snake_case  (				self		,							_snake_case						):



									"""simple docstring"""





									_lowerCAmelCase         =       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...)"""						)

									_lowerCAmelCase         =       []
									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]:
																			_lowerCAmelCase         =       (
																			    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]:
														_lowerCAmelCase         =       (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"""

import unittest

from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    PreTrainedTokenizer,
    is_vision_available,
)
from transformers.pipelines import ImageClassificationPipeline, pipeline
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_tf,
    require_torch,
    require_torch_or_tf,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
		from PIL import Image
else:

		class 							lowercase   :







						@staticmethod
						def        a_	(				*_lowerCamelCase :       Tuple   ,  **_lowerCamelCase :       str							):



							"""simple docstring"""

							pass

@is_pipeline_test
@require_torch_or_tf
@require_vision
class 							lowercase   (     unittest.TestCase):
				__lowerCAmelCase     :     str								= MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
				__lowerCAmelCase     :     Union[str, Any]								= TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING







				def        a_	(				self :       Tuple   ,  _lowerCamelCase :       Any   ,  _lowerCamelCase :       str   ,  _lowerCamelCase :       Optional[Any]							):



					"""simple docstring"""

					A_	:					List[str]						 =		ImageClassificationPipeline(model=_lowerCamelCase   ,  image_processor=_lowerCamelCase   ,  top_k=2							)
					A_	:					Tuple						 =		[
					    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''							),
					    '''http://images.cocodataset.org/val2017/000000039769.jpg''',
					]
					return image_classifier, examples







				def        a_	(				self :       Optional[Any]   ,  _lowerCamelCase :       Optional[int]   ,  _lowerCamelCase :       Optional[Any]							):



					"""simple docstring"""

					A_	:					int						 =		image_classifier('''./tests/fixtures/tests_samples/COCO/000000039769.png'''							)

					self.assertEqual(
					    _lowerCamelCase   ,  [
					        {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					        {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					    ]   ,  )

					import datasets

					A_	:					Optional[Any]						 =		datasets.load_dataset('''hf-internal-testing/fixtures_image_utils'''   ,  '''image'''   ,  split='''test'''							)

					# Accepts URL + PIL.Image + lists
					A_	:					Union[str, Any]						 =		image_classifier(
					    [
					        Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''							),
					        '''http://images.cocodataset.org/val2017/000000039769.jpg''',
					        # RGBA
					        dataset[0]['''file'''],
					        # LA
					        dataset[1]['''file'''],
					        # L
					        dataset[2]['''file'''],
					    ]							)
					self.assertEqual(
					    _lowerCamelCase   ,  [
					        [
					            {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					            {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					        ],
					        [
					            {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					            {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					        ],
					        [
					            {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					            {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					        ],
					        [
					            {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					            {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					        ],
					        [
					            {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					            {'''score''': ANY(_lowerCamelCase							), '''label''': ANY(_lowerCamelCase							)},
					        ],
					    ]   ,  )







				@require_torch
				def        a_	(				self :       Dict							):



					"""simple docstring"""

					A_	:					Optional[int]						 =		'''hf-internal-testing/tiny-random-vit'''
					A_	:					Tuple						 =		pipeline('''image-classification'''   ,  model=_lowerCamelCase							)

					A_	:					Optional[int]						 =		image_classifier('''http://images.cocodataset.org/val2017/000000039769.jpg'''							)
					self.assertEqual(
					    nested_simplify(_lowerCamelCase   ,  decimals=4							)   ,  [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}]   ,  )

					A_	:					str						 =		image_classifier(
					    [
					        '''http://images.cocodataset.org/val2017/000000039769.jpg''',
					        '''http://images.cocodataset.org/val2017/000000039769.jpg''',
					    ]   ,  top_k=2   ,  )
					self.assertEqual(
					    nested_simplify(_lowerCamelCase   ,  decimals=4							)   ,  [
					        [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}],
					        [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}],
					    ]   ,  )







				@require_tf
				def        a_	(				self :       Tuple							):



					"""simple docstring"""

					A_	:					List[str]						 =		'''hf-internal-testing/tiny-random-vit'''
					A_	:					Optional[int]						 =		pipeline('''image-classification'''   ,  model=_lowerCamelCase   ,  framework='''tf'''							)

					A_	:					Tuple						 =		image_classifier('''http://images.cocodataset.org/val2017/000000039769.jpg'''							)
					self.assertEqual(
					    nested_simplify(_lowerCamelCase   ,  decimals=4							)   ,  [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}]   ,  )

					A_	:					Optional[Any]						 =		image_classifier(
					    [
					        '''http://images.cocodataset.org/val2017/000000039769.jpg''',
					        '''http://images.cocodataset.org/val2017/000000039769.jpg''',
					    ]   ,  top_k=2   ,  )
					self.assertEqual(
					    nested_simplify(_lowerCamelCase   ,  decimals=4							)   ,  [
					        [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}],
					        [{'''label''': '''LABEL_1''', '''score''': 0.574}, {'''label''': '''LABEL_0''', '''score''': 0.426}],
					    ]   ,  )







				def        a_	(				self :       Dict							):



					"""simple docstring"""

					A_	:					Any						 =		PreTrainedTokenizer()

					# Assert that the pipeline can be initialized with a feature extractor that is not in any mapping
					A_	:					List[Any]						 =		pipeline(
					    '''image-classification'''   ,  model='''hf-internal-testing/tiny-random-vit'''   ,  tokenizer=_lowerCamelCase							)

					self.assertIs(image_classifier.tokenizer   ,  _lowerCamelCase							)







				@slow
				@require_torch
				def        a_	(				self :       List[str]							):



					"""simple docstring"""

					A_	:					List[Any]						 =		pipeline('''image-classification'''   ,  model='''deepmind/vision-perceiver-conv'''							)
					A_	:					Optional[Any]						 =		image_classifier('''http://images.cocodataset.org/val2017/000000039769.jpg'''							)
					self.assertEqual(
					    nested_simplify(_lowerCamelCase   ,  decimals=4							)   ,  [
					        {'''score''': 0.4385, '''label''': '''tabby, tabby cat'''},
					        {'''score''': 0.321, '''label''': '''tiger cat'''},
					        {'''score''': 0.0502, '''label''': '''Egyptian cat'''},
					        {'''score''': 0.0137, '''label''': '''crib, cot'''},
					        {'''score''': 0.007, '''label''': '''radiator'''},
					    ]   ,  )

					A_	:					Dict						 =		pipeline('''image-classification'''   ,  model='''deepmind/vision-perceiver-fourier'''							)
					A_	:					str						 =		image_classifier('''http://images.cocodataset.org/val2017/000000039769.jpg'''							)
					self.assertEqual(
					    nested_simplify(_lowerCamelCase   ,  decimals=4							)   ,  [
					        {'''score''': 0.5658, '''label''': '''tabby, tabby cat'''},
					        {'''score''': 0.1309, '''label''': '''tiger cat'''},
					        {'''score''': 0.0722, '''label''': '''Egyptian cat'''},
					        {'''score''': 0.0707, '''label''': '''remote control, remote'''},
					        {'''score''': 0.0082, '''label''': '''computer keyboard, keypad'''},
					    ]   ,  )

					A_	:					Optional[int]						 =		pipeline('''image-classification'''   ,  model='''deepmind/vision-perceiver-learned'''							)
					A_	:					int						 =		image_classifier('''http://images.cocodataset.org/val2017/000000039769.jpg'''							)
					self.assertEqual(
					    nested_simplify(_lowerCamelCase   ,  decimals=4							)   ,  [
					        {'''score''': 0.3022, '''label''': '''tabby, tabby cat'''},
					        {'''score''': 0.2362, '''label''': '''Egyptian cat'''},
					        {'''score''': 0.1856, '''label''': '''tiger cat'''},
					        {'''score''': 0.0324, '''label''': '''remote control, remote'''},
					        {'''score''': 0.0096, '''label''': '''quilt, comforter, comfort, puff'''},
					    ]   ,  )





