



"""simple docstring"""





import importlib
import os
import sys


# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append('''.''')




def 	UpperCAmelCase     (		A	:						int       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		test_file.split(os.path.sep       )
		if components[0:2] != ["tests", "models"]:
				raise ValueError(
				    '`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got '
				    f'{test_file} instead.'       )
		_UpperCAmelCase							 =		components[-1]
		if not test_fn.endswith('py'       ):
				raise ValueError(f'`test_file` should be a python file. Got {test_fn} instead.'       )
		if not test_fn.startswith('test_modeling_'       ):
				raise ValueError(
				    f'`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.'       )

		_UpperCAmelCase							 =		components[:-1] + [test_fn.replace('.py'     ,				''       )]
		_UpperCAmelCase							 =		'.'.join(A       )

		return test_module_path




def 	UpperCAmelCase     (		A	:						Optional[Any]       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		get_module_path(A       )
		_UpperCAmelCase							 =		importlib.import_module(A       )

		return test_module




def 	UpperCAmelCase     (		A	:						Dict       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		[]
		_UpperCAmelCase							 =		get_test_module(A       )
		for attr in dir(A       ):
				if attr.endswith('ModelTester'       ):
						tester_classes.append(getattr(A     ,				A       )       )

    # sort with class names
		return sorted(A     ,				key=lambda A       : x.__name__       )




def 	UpperCAmelCase     (		A	:						Optional[int]       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		[]
		_UpperCAmelCase							 =		get_test_module(A       )
		for attr in dir(A       ):
				_UpperCAmelCase							 =		getattr(A     ,				A       )
				# (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
				# `all_model_classes` is not empty (which also excludes other special classes).
				_UpperCAmelCase							 =		getattr(A     ,				'all_model_classes'     ,				[]       )
				if len(A       ) > 0:
						test_classes.append(A       )

    # sort with class names
		return sorted(A     ,				key=lambda A       : x.__name__       )




def 	UpperCAmelCase     (		A	:						int       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		get_test_classes(A       )
		_UpperCAmelCase							 =		set()
		for test_class in test_classes:
				model_classes.update(test_class.all_model_classes       )

		# sort with class names
		return sorted(A     ,				key=lambda A       : x.__name__       )




def 	UpperCAmelCase     (		A	:						Dict       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		test_class()
		if hasattr(A     ,				'setUp'       ):
				test.setUp()

		_UpperCAmelCase							 =		None
		if hasattr(A     ,				'model_tester'       ):
				# `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
				if test.model_tester is not None:
						_UpperCAmelCase							 =		test.model_tester.__class__

		return model_tester




def 	UpperCAmelCase     (		A	:						Any     ,				A	:						int       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		get_test_classes(A       )

		_UpperCAmelCase							 =		[]
		for test_class in test_classes:
				if model_class in test_class.all_model_classes:
						target_test_classes.append(A       )

    # sort with class names
		return sorted(A     ,				key=lambda A       : x.__name__       )




def 	UpperCAmelCase     (		A	:						str     ,				A	:						Dict       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		get_test_classes_for_model(A     ,				A       )

		_UpperCAmelCase							 =		[]
		for test_class in test_classes:
				_UpperCAmelCase							 =		get_model_tester_from_test_class(A       )
				if tester_class is not None:
						tester_classes.append(A       )

    # sort with class names
		return sorted(A     ,				key=lambda A       : x.__name__       )




def 	UpperCAmelCase     (		A	:						Optional[Any]       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		get_test_classes(A       )
		_UpperCAmelCase							 =		{test_class: get_model_tester_from_test_class(A       ) for test_class in test_classes}
		return test_tester_mapping




def 	UpperCAmelCase     (		A	:						Any       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		get_model_classes(A       )
		_UpperCAmelCase							 =		{
		    model_class: get_test_classes_for_model(A     ,				A       ) for model_class in model_classes
		}
		return model_test_mapping




def 	UpperCAmelCase     (		A	:						int       ):

		'''simple docstring'''


		_UpperCAmelCase							 =		get_model_classes(A       )
		_UpperCAmelCase							 =		{
		    model_class: get_tester_classes_for_model(A     ,				A       ) for model_class in model_classes
		}
		return model_to_tester_mapping






def 	UpperCAmelCase     (		A	:						List[Any]       ):

		'''simple docstring'''


		if isinstance(A     ,				A       ):
				return o
		elif isinstance(A     ,				A       ):
				return o.__name__
		elif isinstance(A     ,				(list, tuple)       ):
				return [to_json(A       ) for x in o]
		elif isinstance(A     ,				A       ):
				return {to_json(A       ): to_json(A       ) for k, v in o.items()}
		else:
				return o







"""simple docstring"""





import unittest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TextaTextGenerationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch
from transformers.utils import is_torch_available

from .test_pipelines_common import ANY


if is_torch_available():
					import torch




@is_pipeline_test
class 			lowercase__			(      unittest.TestCase    ):
							'''simple docstring'''







							_UpperCAmelCase      				=					MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
							_UpperCAmelCase      				=					TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING






							def        lowerCamelCase_   (  self	,       snake_case	,       snake_case	,       snake_case						)			->							Dict:
									_UpperCAmelCase							 =		TextaTextGenerationPipeline(model=snake_case	,       tokenizer=snake_case						)
									return generator, ["Something to write", "Something else"]






							def        lowerCamelCase_   (  self	,       snake_case	,       snake_case						)			->							Dict:
									_UpperCAmelCase							 =		generator('Something there'						)
									self.assertEqual(snake_case	,       [{'generated_text': ANY(snake_case						)}]						)
									# These are encoder decoder, they don't just append to incoming string
									self.assertFalse(outputs[0]['generated_text'].startswith('Something there'						)						)

									_UpperCAmelCase							 =		generator(['This is great !', 'Something else']	,       num_return_sequences=2	,       do_sample=snake_case						)
									self.assertEqual(
									    snake_case	,       [
									        [{'generated_text': ANY(snake_case						)}, {'generated_text': ANY(snake_case						)}],
									        [{'generated_text': ANY(snake_case						)}, {'generated_text': ANY(snake_case						)}],
									    ]	,       )

									_UpperCAmelCase							 =		generator(
									    ['This is great !', 'Something else']	,       num_return_sequences=2	,       batch_size=2	,       do_sample=snake_case						)
									self.assertEqual(
									    snake_case	,       [
									        [{'generated_text': ANY(snake_case						)}, {'generated_text': ANY(snake_case						)}],
									        [{'generated_text': ANY(snake_case						)}, {'generated_text': ANY(snake_case						)}],
									    ]	,       )

									with self.assertRaises(snake_case						):
											generator(4						)






							@require_torch
							def        lowerCamelCase_   (  self						)			->							Dict:
									_UpperCAmelCase							 =		pipeline('text2text-generation'	,       model='patrickvonplaten/t5-tiny-random'	,       framework='pt'						)
									# do_sample=False necessary for reproducibility
									_UpperCAmelCase							 =		generator('Something there'	,       do_sample=snake_case						)
									self.assertEqual(snake_case	,       [{'generated_text': ''}]						)

									_UpperCAmelCase							 =		3
									_UpperCAmelCase							 =		generator(
									    'Something there'	,       num_return_sequences=snake_case	,       num_beams=snake_case	,       )
									_UpperCAmelCase							 =		[
									    {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide Beide'},
									    {'generated_text': 'Beide Beide Beide Beide Beide Beide Beide Beide'},
									    {'generated_text': ''},
									]
									self.assertEqual(snake_case	,       snake_case						)

									_UpperCAmelCase							 =		generator('This is a test'	,       do_sample=snake_case	,       num_return_sequences=2	,       return_tensors=snake_case						)
									self.assertEqual(
									    snake_case	,       [
									        {'generated_token_ids': ANY(torch.Tensor						)},
									        {'generated_token_ids': ANY(torch.Tensor						)},
									    ]	,       )
									_UpperCAmelCase							 =		generator.model.config.eos_token_id
									_UpperCAmelCase							 =		'<pad>'
									_UpperCAmelCase							 =		generator(
									    ['This is a test', 'This is a second test']	,       do_sample=snake_case	,       num_return_sequences=2	,       batch_size=2	,       return_tensors=snake_case	,       )
									self.assertEqual(
									    snake_case	,       [
									        [
									            {'generated_token_ids': ANY(torch.Tensor						)},
									            {'generated_token_ids': ANY(torch.Tensor						)},
									        ],
									        [
									            {'generated_token_ids': ANY(torch.Tensor						)},
									            {'generated_token_ids': ANY(torch.Tensor						)},
									        ],
									    ]	,       )






							@require_tf
							def        lowerCamelCase_   (  self						)			->							Any:
									_UpperCAmelCase							 =		pipeline('text2text-generation'	,       model='patrickvonplaten/t5-tiny-random'	,       framework='tf'						)
									# do_sample=False necessary for reproducibility
									_UpperCAmelCase							 =		generator('Something there'	,       do_sample=snake_case						)
									self.assertEqual(snake_case	,       [{'generated_text': ''}]						)


