






"""simple docstring"""




import argparse
import glob
import inspect
import os
import re
import unittest

from get_test_info import get_test_classes

from tests.test_pipeline_mixin import pipeline_test_mapping


_snake_case					   =     {}
for task, _ in pipeline_test_mapping.items():
	_snake_case					   =     {'pt': None, 'tf': None}


# DO **NOT** add item to this set (unless the reason is approved)
_snake_case					   =     {
    'tests/models/esm/test_modeling_esmfold.py',  # The pipeline test mapping is added to `test_modeling_esm.py`
}

def     lowerCAmelCase__  (  UpperCamelCase__       ):



		'''simple docstring'''

		if "ModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
				return "pt"
		elif "TFModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
				return "tf"
		elif "FlaxModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
				return "flax"
		else:
				return None

def     lowerCAmelCase__  (  UpperCamelCase__  ,     UpperCamelCase__       ):



		'''simple docstring'''
		# Use the cached results
		if PIPELINE_TEST_MAPPING[task].get(UpperCamelCase__  ,     UpperCamelCase__       ) is not None:
				return PIPELINE_TEST_MAPPING[task][framework]

		_a						: Union[str, Any]    =			pipeline_test_mapping[task]["""test"""]
		_a						: Union[str, Any]    =			None

		if framework == "pt":
				_a						: Tuple    =			getattr(UpperCamelCase__  ,     """model_mapping"""  ,     UpperCamelCase__       )
		elif framework == "tf":
				_a						: int    =			getattr(UpperCamelCase__  ,     """tf_model_mapping"""  ,     UpperCamelCase__       )

		if mapping is not None:
				_a						: List[str]    =			dict(mapping.items()       )

		# cache the results
		_a						: List[str]    =			mapping
		return mapping

def     lowerCAmelCase__  (  UpperCamelCase__  ,     UpperCamelCase__       ):



		'''simple docstring'''
		_a						: List[str]    =			get_framework(UpperCamelCase__       )
		if framework is None:
				return None
		_a						: Optional[int]    =			get_mapping_for_task(UpperCamelCase__  ,     UpperCamelCase__       )
		if mapping is None:
				return None

		_a						: Optional[Any]    =			list({model_class.config_class for model_class in test_class.all_model_classes}       )
		if len(UpperCamelCase__       ) != 1:
				raise ValueError("""There should be exactly one configuration class from `test_class.all_model_classes`."""       )

		# This could be a list/tuple of model classes, but it's rare.
		_a						: Any    =			mapping.get(config_classes[0]  ,     UpperCamelCase__       )
		if isinstance(UpperCamelCase__  ,     (tuple, list)       ):
				_a						: Union[str, Any]    =			sorted(UpperCamelCase__  ,     key=lambda UpperCamelCase__       : x.__name__       )

		return model_class

def     lowerCAmelCase__  (  UpperCamelCase__       ):



		'''simple docstring'''
		_a						: int    =			[(task, get_model_for_pipeline_test(UpperCamelCase__  ,     UpperCamelCase__       )) for task in pipeline_test_mapping]
		_a						: str    =			sorted([(task, model) for task, model in mapping if model is not None]  ,     key=lambda UpperCamelCase__       : x[0]       )

		return dict(UpperCamelCase__       )

def     lowerCAmelCase__  (  UpperCamelCase__       ):



		'''simple docstring'''
		_a						: Optional[Any]    =			get_framework(UpperCamelCase__       )
		if framework == "pt":
				_a						: List[str]    =			"""torch"""
		_a						: str    =			"""{}"""

		_a						: Any    =			get_pipeline_model_mapping(UpperCamelCase__       )
		if len(UpperCamelCase__       ) == 0:
				return ""

		_a						: Union[str, Any]    =			[]
		for task, model_classes in mapping.items():
				if isinstance(UpperCamelCase__  ,     (tuple, list)       ):
						# A list/tuple of model classes
						_a						: List[Any]    =			"""(""" + """, """.join([x.__name__ for x in model_classes]       ) + """)"""
				else:
						# A single model class
						_a						: List[str]    =			model_classes.__name__
				texts.append(F"""\"{task}\": {value}"""       )
		_a						: Any    =			"""{""" + """, """.join(UpperCamelCase__       ) + """}"""
		_a						: str    =			F"""pipeline_model_mapping = {text} if is_{framework}_available() else {default_value}"""

		return text

def     lowerCAmelCase__  (  UpperCamelCase__       ):



		'''simple docstring'''
		_a						: List[str]    =			{"""ModelTesterMixin""", """TFModelTesterMixin""", """FlaxModelTesterMixin"""}
		if not issubclass(UpperCamelCase__  ,     unittest.TestCase       ):
				return False
		return len(base_class_names.intersection([x.__name__ for x in test_class.__bases__]       )       ) > 0

def     lowerCAmelCase__  (  UpperCamelCase__       ):



		'''simple docstring'''
		_a						: Tuple    =			[x for x in get_test_classes(UpperCamelCase__       ) if is_valid_test_class(UpperCamelCase__       )]

		_a						: Union[str, Any]    =			None
		for test_class in test_classes:
				# If a test class has defined `pipeline_model_mapping`, let's take it
				if getattr(UpperCamelCase__  ,     """pipeline_model_mapping"""  ,     UpperCamelCase__       ) is not None:
						_a						: Optional[Any]    =			test_class
						break
				# Take the test class with the shortest name (just a heuristic)
		if target_test_class is None and len(UpperCamelCase__       ) > 0:
				_a						: Optional[Any]    =			sorted(UpperCamelCase__  ,     key=lambda UpperCamelCase__       : (len(x.__name__       ), x.__name__)       )[0]

		return target_test_class

def     lowerCAmelCase__  (  UpperCamelCase__  ,     UpperCamelCase__  ,     UpperCamelCase__       ):



		'''simple docstring'''
		_a						: Tuple    =			start_idx
		for idx, line in enumerate(lines[start_idx:]       ):
				_a						: Tuple    =			len(UpperCamelCase__       ) - len(line.lstrip()       )
				if idx == 0 or indent > indent_level or (indent == indent_level and line.strip() == ")"):
						_a						: str    =			start_idx + idx
				elif idx > 0 and indent <= indent_level:
						# Outside the definition block of `pipeline_model_mapping`
						break

		return end_idx

def     lowerCAmelCase__  (  UpperCamelCase__  ,     UpperCamelCase__=False       ):



		'''simple docstring'''
		if getattr(UpperCamelCase__  ,     """pipeline_model_mapping"""  ,     UpperCamelCase__       ) is not None:
				if not overwrite:
						return "", -1

		_a						: Optional[Any]    =			get_pipeline_model_mapping_string(UpperCamelCase__       )
		if len(UpperCamelCase__       ) == 0:
				return "", -1
		_a						: Union[str, Any]    =			line_to_add + """\n"""

		# The code defined the class `test_class`
		_a						: str    =			inspect.getsourcelines(UpperCamelCase__       )
		# `inspect` gives the code for an object, including decorator(s) if any.
		# We (only) need the exact line of the class definition.
		for idx, line in enumerate(UpperCamelCase__       ):
				if line.lstrip().startswith("""class """       ):
						_a						: Dict    =			class_lines[idx:]
						class_start_line_no += idx
						break
		_a						: List[Any]    =			class_start_line_no + len(UpperCamelCase__       ) - 1

		# The index in `class_lines` that starts the definition of `all_model_classes`, `all_generative_model_classes` or
		# `pipeline_model_mapping`. This assumes they are defined in such order, and we take the start index of the last
		# block that appears in a `test_class`.
		_a						: int    =			None
		# The indent level of the line at `class_lines[start_idx]` (if defined)
		_a						: List[Any]    =			0
		# To record if `pipeline_model_mapping` is found in `test_class`.
		_a						: Any    =			None
		for idx, line in enumerate(UpperCamelCase__       ):
				if line.strip().startswith("""all_model_classes = """       ):
						_a						: List[str]    =			len(UpperCamelCase__       ) - len(line.lstrip()       )
						_a						: int    =			idx
				elif line.strip().startswith("""all_generative_model_classes = """       ):
						_a						: Union[str, Any]    =			len(UpperCamelCase__       ) - len(line.lstrip()       )
						_a						: Optional[int]    =			idx
				elif line.strip().startswith("""pipeline_model_mapping = """       ):
						_a						: Dict    =			len(UpperCamelCase__       ) - len(line.lstrip()       )
						_a						: int    =			idx
						_a						: Any    =			line
						break

		if start_idx is None:
				return "", -1
		# Find the ending index (inclusive) of the above found block.
		_a						: str    =			find_block_ending(UpperCamelCase__  ,     UpperCamelCase__  ,     UpperCamelCase__       )

		# Extract `is_xxx_available()` from existing blocks: some models require specific libraries like `timm` and use
		# `is_timm_available()` instead of `is_torch_available()`.
		# Keep leading and trailing whitespaces
		_a						: Tuple    =			re.compile(R"""\s(is_\S+?_available\(\))\s"""       )
		for line in class_lines[start_idx : end_idx + 1]:
				_a						: Tuple    =			r.search(UpperCamelCase__       )
				if backend_condition is not None:
						# replace the leading and trailing whitespaces to the space character " ".
						_a						: int    =			""" """ + backend_condition[0][1:-1] + """ """
						_a						: List[str]    =			r.sub(UpperCamelCase__  ,     UpperCamelCase__       )
						break

		if def_line is None:
				# `pipeline_model_mapping` is not defined. The target index is set to the ending index (inclusive) of
				# `all_model_classes` or `all_generative_model_classes`.
				_a						: int    =			end_idx
		else:
				# `pipeline_model_mapping` is defined. The target index is set to be one **BEFORE** its start index.
				_a						: List[str]    =			start_idx - 1
				# mark the lines of the currently existing `pipeline_model_mapping` to be removed.
				for idx in range(UpperCamelCase__  ,     end_idx + 1       ):
						# These lines are going to be removed before writing to the test file.
						_a						: Dict    =			None  # noqa

				# Make sure the test class is a subclass of `PipelineTesterMixin`.
		_a						: List[Any]    =			[x.__name__ for x in test_class.__bases__]
		if "PipelineTesterMixin" not in parent_classes:
				# Put `PipelineTesterMixin` just before `unittest.TestCase`
				_a						: int    =			[x for x in parent_classes if x != """TestCase"""] + ["""PipelineTesterMixin"""]
				if "TestCase" in parent_classes:
						# Here we **assume** the original string is always with `unittest.TestCase`.
						_parent_classes.append("""unittest.TestCase"""       )
				_a						: List[Any]    =			""", """.join(_parent_classes       )
				for idx, line in enumerate(UpperCamelCase__       ):
						# Find the ending of the declaration of `test_class`
						if line.strip().endswith("""):"""       ):
								# mark the lines of the declaration of `test_class` to be removed
								for _idx in range(idx + 1       ):
										_a						: int    =			None  # noqa
								break
								# Add the new, one-line, class declaration for `test_class`
				_a						: Union[str, Any]    =			F"""class {test_class.__name__}({parent_classes}):\n"""

		# Add indentation
		_a						: str    =			""" """ * indent_level + line_to_add
		# Insert `pipeline_model_mapping` to `class_lines`.
		# (The line at `target_idx` should be kept by definition!)
		_a						: Optional[int]    =			class_lines[: target_idx + 1] + [line_to_add] + class_lines[target_idx + 1 :]
		# Remove the lines that are marked to be removed
		_a						: Optional[Any]    =			[x for x in class_lines if x is not None]

		# Move from test class to module (in order to write to the test file)
		_a						: List[Any]    =			inspect.getsourcelines(inspect.getmodule(UpperCamelCase__       )       )[0]
		# Be careful with the 1-off between line numbers and array indices
		_a						: int    =			module_lines[: class_start_line_no - 1] + class_lines + module_lines[class_end_line_no:]
		_a						: List[Any]    =			"""""".join(UpperCamelCase__       )

		_a						: int    =			inspect.getsourcefile(UpperCamelCase__       )
		with open(UpperCamelCase__  ,     """w"""  ,     encoding="""UTF-8"""  ,     newline="""\n"""       ) as fp:
				fp.write(UpperCamelCase__       )

		return line_to_add

def     lowerCAmelCase__  (  UpperCamelCase__  ,     UpperCamelCase__=False       ):



		'''simple docstring'''
		_a						: Optional[int]    =			find_test_class(UpperCamelCase__       )
		if test_class:
				add_pipeline_model_mapping(UpperCamelCase__  ,     overwrite=UpperCamelCase__       )


if __name__ == "__main__":
	_snake_case					   =     argparse.ArgumentParser()
	parser.add_argument(
	    '--test_file', type=str, help='A path to the test file, starting with the repository\'s `tests` directory.'
	)
	parser.add_argument(
	    '--all',
	    action='store_true',
	    help='If to check and modify all test files.',
	)
	parser.add_argument(
	    '--overwrite',
	    action='store_true',
	    help='If to overwrite a test class if it has already defined `pipeline_model_mapping`.',
	)
	_snake_case					   =     parser.parse_args()

	if not args.all and not args.test_file:
		raise ValueError('Please specify either `test_file` or pass `--all` to check/modify all test files.')
	elif args.all and args.test_file:
		raise ValueError('Only one of `--test_file` and `--all` could be specified.')

	_snake_case					   =     []
	if args.test_file:
		_snake_case					   =     [args.test_file]
	else:
		_snake_case					   =     os.path.join('tests', 'models', '**', 'test_modeling_*.py')
		for test_file in glob.glob(pattern):
			# `Flax` is not concerned at this moment
			if not test_file.startswith('test_modeling_flax_'):
				test_files.append(test_file)

	for test_file in test_files:
		if test_file in TEST_FILE_TO_IGNORE:
			print(F'''[SKIPPED] {test_file} is skipped as it is in `TEST_FILE_TO_IGNORE` in the file {__file__}.''')
			continue
		add_pipeline_model_mapping_to_test_file(test_file, overwrite=args.overwrite)









"""simple docstring"""




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

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

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

# fmt: off
_snake_case					   =     '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_   ):
 UpperCamelCase      : Any    =      VOCAB_FILES_NAMES
 UpperCamelCase      : Tuple    =      LlamaTokenizer
 UpperCamelCase      : Union[str, Any]    =      '''left'''
 UpperCamelCase      : str    =      ['''input_ids''', '''attention_mask''']


 def __init__(  self	:		Union[str, Any]							,		UpperCAmelCase__	:		Optional[int]=None							,		UpperCAmelCase__	:		Dict=None							,		UpperCAmelCase__	:		Optional[int]=False							,		UpperCAmelCase__	:		Optional[Any]="<unk>"							,		UpperCAmelCase__	:		str="<s>"							,		UpperCAmelCase__	:		List[Any]="</s>"							,		UpperCAmelCase__	:		Tuple=True							,		UpperCAmelCase__	:		int=False							,		**UpperCAmelCase__	:		Tuple							,		)      -> Dict:
   super().__init__(
       vocab_file=UpperCAmelCase__							,		tokenizer_file=UpperCAmelCase__							,		clean_up_tokenization_spaces=UpperCAmelCase__							,		unk_token=UpperCAmelCase__							,		bos_token=UpperCAmelCase__							,		eos_token=UpperCAmelCase__							,		**UpperCAmelCase__							,		)
   _a						: List[str]    =			add_bos_token
   _a						: Union[str, Any]    =			add_eos_token
   self.update_post_processor()

   _a						: List[str]    =			vocab_file
   _a						: Union[str, Any]    =			False if not self.vocab_file else True


 def _lowercase			(  self	:		List[str]							)      -> int:
   _a						: Dict    =			self.bos_token
   _a						: Union[str, Any]    =			self.bos_token_id

   _a						: int    =			self.eos_token
   _a						: str    =			self.eos_token_id

   _a						: Optional[Any]    =			f"""{(bos+':0 ') * self.add_bos_token}$A:0{(' '+eos+':0') * self.add_eos_token}"""
   _a						: str    =			f"""{single}{(' '+bos+':1') * self.add_bos_token} $B:1{(' '+eos+':1') * self.add_eos_token}"""

   _a						: Optional[int]    =			[]
   if self.add_bos_token:
     special_tokens.append((bos, bos_token_id)							)
   if self.add_eos_token:
     special_tokens.append((eos, eos_token_id)							)
   _a						: str    =			processors.TemplateProcessing(
       single=UpperCAmelCase__							,		pair=UpperCAmelCase__							,		special_tokens=UpperCAmelCase__							)


 @property
 def _lowercase			(  self	:		Optional[int]							)      -> Optional[Any]:
   return self._add_eos_token


 @property
 def _lowercase			(  self	:		Dict							)      -> str:
   return self._add_bos_token


 @add_eos_token.setter
 def _lowercase			(  self	:		Any							,		UpperCAmelCase__	:		int							)      -> List[str]:
   _a						: Any    =			value
   self.update_post_processor()


 @add_bos_token.setter
 def _lowercase			(  self	:		Any							,		UpperCAmelCase__	:		int							)      -> List[str]:
   _a						: Optional[Any]    =			value
   self.update_post_processor()


 def _lowercase			(  self	:		Dict							,		UpperCAmelCase__	:		str							,		UpperCAmelCase__	:		Optional[str] = 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(UpperCAmelCase__							):
     logger.error(f"""Vocabulary path ({save_directory}) should be a directory"""							)
     return
   _a						: str    =			os.path.join(
       UpperCAmelCase__							,		(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]							)

   if os.path.abspath(self.vocab_file							) != os.path.abspath(UpperCAmelCase__							):
     copyfile(self.vocab_file							,		UpperCAmelCase__							)

   return (out_vocab_file,)







 def _lowercase			(  self	:		Tuple							,		UpperCAmelCase__	:		"Conversation"							)      -> Optional[Any]:
   _a						: str    =			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...)"""							)

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

