






"""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   ,						_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
import unittest

from transformers.models.bertweet.tokenization_bertweet import VOCAB_FILES_NAMES, BertweetTokenizer

from ...test_tokenization_common import TokenizerTesterMixin






class  UpperCamelCase    (			snake_case_	,  unittest.TestCase   ):
 UpperCamelCase      : Union[str, Any]    =      BertweetTokenizer
 UpperCamelCase      : Optional[Any]    =      False


 def _lowercase			(  self	:		Dict							)      -> List[Any]:
   super().setUp()

   # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
   _a						: Tuple    =			["""I""", """m""", """V@@""", """R@@""", """r""", """e@@"""]
   _a						: str    =			dict(zip(UpperCAmelCase__							,		range(len(UpperCAmelCase__							)							)							)							)
   _a						: Dict    =			["""#version: 0.2""", """a m</w>"""]
   _a						: int    =			{"""unk_token""": """<unk>"""}

   _a						: Union[str, Any]    =			os.path.join(self.tmpdirname							,		VOCAB_FILES_NAMES["""vocab_file"""]							)
   _a						: List[Any]    =			os.path.join(self.tmpdirname							,		VOCAB_FILES_NAMES["""merges_file"""]							)
   with open(self.vocab_file							,		"""w"""							,		encoding="""utf-8"""							) as fp:
     for token in vocab_tokens:
       fp.write(f"""{token} {vocab_tokens[token]}\n"""							)
   with open(self.merges_file							,		"""w"""							,		encoding="""utf-8"""							) as fp:
     fp.write("""\n""".join(UpperCAmelCase__							)							)


 def _lowercase			(  self	:		Any							,		**UpperCAmelCase__	:		Optional[Any]							)      -> Dict:
   kwargs.update(self.special_tokens_map							)
   return BertweetTokenizer.from_pretrained(self.tmpdirname							,		**UpperCAmelCase__							)


 def _lowercase			(  self	:		Dict							,		UpperCAmelCase__	:		Optional[int]							)      -> Dict:
   _a						: List[str]    =			"""I am VinAI Research"""
   _a						: Optional[int]    =			"""I <unk> m V<unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>"""
   return input_text, output_text







 def _lowercase			(  self	:		Tuple							)      -> Optional[int]:
   _a						: Optional[int]    =			BertweetTokenizer(self.vocab_file							,		self.merges_file							,		**self.special_tokens_map							)
   _a						: Tuple    =			"""I am VinAI Research"""
   _a						: Dict    =			"""I a@@ m V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h""".split()
   _a						: str    =			tokenizer.tokenize(UpperCAmelCase__							)
   self.assertListEqual(UpperCAmelCase__							,		UpperCAmelCase__							)

   _a						: Tuple    =			tokens + [tokenizer.unk_token]

   _a						: Tuple    =			[4, 3, 5, 6, 3, 3, 3, 4, 7, 9, 3, 9, 3, 3, 3, 3, 3]
   self.assertListEqual(tokenizer.convert_tokens_to_ids(UpperCAmelCase__							)							,		UpperCAmelCase__							)

