




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


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


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






def  snake_case (							A      )							->							Union[str, Any]:




	'''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  snake_case (							A						,       A      )							->							Any:




	'''simple docstring'''


	if PIPELINE_TEST_MAPPING[task].get(snake_case__						,       snake_case__      ) is not None:
		return PIPELINE_TEST_MAPPING[task][framework]

	lowerCamelCase_							:		Dict							       =							pipeline_test_mapping[task]['test']
	lowerCamelCase_							:		int							       =							None

	if framework == "pt":
		lowerCamelCase_							:		int							       =							getattr(snake_case__						,       'model_mapping'						,       snake_case__      )
	elif framework == "tf":
		lowerCamelCase_							:		List[str]							       =							getattr(snake_case__						,       'tf_model_mapping'						,       snake_case__      )

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

	# cache the results
	lowerCamelCase_							:		int							       =							mapping
	return mapping






def  snake_case (							A						,       A      )							->							str:




	'''simple docstring'''


	lowerCamelCase_							:		List[str]							       =							get_framework(snake_case__      )
	if framework is None:
		return None
	lowerCamelCase_							:		List[str]							       =							get_mapping_for_task(snake_case__						,       snake_case__      )
	if mapping is None:
		return None

	lowerCamelCase_							:		Union[str, Any]							       =							list({model_class.config_class for model_class in test_class.all_model_classes}      )
	if len(snake_case__      ) != 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.
	lowerCamelCase_							:		int							       =							mapping.get(config_classes[0]						,       snake_case__      )
	if isinstance(snake_case__						,       (tuple, list)      ):
		lowerCamelCase_							:		Union[str, Any]							       =							sorted(snake_case__						,       key=lambda A      : x.__name__      )

	return model_class






def  snake_case (							A      )							->							List[Any]:




	'''simple docstring'''


	lowerCamelCase_							:		Optional[int]							       =							[(task, get_model_for_pipeline_test(snake_case__						,       snake_case__      )) for task in pipeline_test_mapping]
	lowerCamelCase_							:		Optional[int]							       =							sorted([(task, model) for task, model in mapping if model is not None]						,       key=lambda A      : x[0]      )

	return dict(snake_case__      )






def  snake_case (							A      )							->							str:




	'''simple docstring'''


	lowerCamelCase_							:		int							       =							get_framework(snake_case__      )
	if framework == "pt":
		lowerCamelCase_							:		Dict							       =							'torch'
	lowerCamelCase_							:		Optional[int]							       =							'{}'

	lowerCamelCase_							:		List[Any]							       =							get_pipeline_model_mapping(snake_case__      )
	if len(snake_case__      ) == 0:
		return ""

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

	return text






def  snake_case (							A      )							->							Any:




	'''simple docstring'''


	lowerCamelCase_							:		Dict							       =							{'ModelTesterMixin', 'TFModelTesterMixin', 'FlaxModelTesterMixin'}
	if not issubclass(snake_case__						,       unittest.TestCase      ):
		return False
	return len(base_class_names.intersection([x.__name__ for x in test_class.__bases__]      )      ) > 0






def  snake_case (							A      )							->							Dict:




	'''simple docstring'''


	lowerCamelCase_							:		List[str]							       =							[x for x in get_test_classes(snake_case__      ) if is_valid_test_class(snake_case__      )]

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

	return target_test_class






def  snake_case (							A						,       A						,       A      )							->							Any:




	'''simple docstring'''


	lowerCamelCase_							:		Union[str, Any]							       =							start_idx
	for idx, line in enumerate(lines[start_idx:]      ):
		lowerCamelCase_							:		Optional[Any]							       =							len(snake_case__      ) - len(line.lstrip()      )
		if idx == 0 or indent > indent_level or (indent == indent_level and line.strip() == ")"):
			lowerCamelCase_							:		Any							       =							start_idx + idx
		elif idx > 0 and indent <= indent_level:
			# Outside the definition block of `pipeline_model_mapping`
			break

	return end_idx






def  snake_case (							A						,       A=False      )							->							Optional[int]:




	'''simple docstring'''


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

	lowerCamelCase_							:		Optional[Any]							       =							get_pipeline_model_mapping_string(snake_case__      )
	if len(snake_case__      ) == 0:
		return "", -1
	lowerCamelCase_							:		Any							       =							line_to_add + '\n'

	# The code defined the class `test_class`
	lowerCamelCase_       ,      lowerCamelCase_							:		Union[str, Any]							       =							inspect.getsourcelines(snake_case__      )
	# `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(snake_case__      ):
		if line.lstrip().startswith('class '      ):
			lowerCamelCase_							:		Optional[int]							       =							class_lines[idx:]
			class_start_line_no += idx
			break
	lowerCamelCase_							:		Tuple							       =							class_start_line_no + len(snake_case__      ) - 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`.
	lowerCamelCase_							:		List[str]							       =							None
	# The indent level of the line at `class_lines[start_idx]` (if defined)
	lowerCamelCase_							:		Any							       =							0
	# To record if `pipeline_model_mapping` is found in `test_class`.
	lowerCamelCase_							:		Tuple							       =							None
	for idx, line in enumerate(snake_case__      ):
		if line.strip().startswith('all_model_classes = '      ):
			lowerCamelCase_							:		Optional[Any]							       =							len(snake_case__      ) - len(line.lstrip()      )
			lowerCamelCase_							:		str							       =							idx
		elif line.strip().startswith('all_generative_model_classes = '      ):
			lowerCamelCase_							:		Any							       =							len(snake_case__      ) - len(line.lstrip()      )
			lowerCamelCase_							:		Any							       =							idx
		elif line.strip().startswith('pipeline_model_mapping = '      ):
			lowerCamelCase_							:		List[Any]							       =							len(snake_case__      ) - len(line.lstrip()      )
			lowerCamelCase_							:		str							       =							idx
			lowerCamelCase_							:		Optional[int]							       =							line
			break

	if start_idx is None:
		return "", -1
	# Find the ending index (inclusive) of the above found block.
	lowerCamelCase_							:		Optional[Any]							       =							find_block_ending(snake_case__						,       snake_case__						,       snake_case__      )

	# 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
	lowerCamelCase_							:		Tuple							       =							re.compile(R'\s(is_\S+?_available\(\))\s'      )
	for line in class_lines[start_idx : end_idx + 1]:
		lowerCamelCase_							:		Union[str, Any]							       =							r.search(snake_case__      )
		if backend_condition is not None:
			# replace the leading and trailing whitespaces to the space character " ".
			lowerCamelCase_							:		Union[str, Any]							       =							' ' + backend_condition[0][1:-1] + ' '
			lowerCamelCase_							:		int							       =							r.sub(snake_case__						,       snake_case__      )
			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`.
		lowerCamelCase_							:		List[Any]							       =							end_idx
	else:
		# `pipeline_model_mapping` is defined. The target index is set to be one **BEFORE** its start index.
		lowerCamelCase_							:		Optional[Any]							       =							start_idx - 1
		# mark the lines of the currently existing `pipeline_model_mapping` to be removed.
		for idx in range(snake_case__						,       end_idx + 1      ):
			# These lines are going to be removed before writing to the test file.
			lowerCamelCase_							:		Dict							       =							None  # noqa

    # Make sure the test class is a subclass of `PipelineTesterMixin`.
	lowerCamelCase_							:		Optional[Any]							       =							[x.__name__ for x in test_class.__bases__]
	if "PipelineTesterMixin" not in parent_classes:
		# Put `PipelineTesterMixin` just before `unittest.TestCase`
		lowerCamelCase_							:		List[str]							       =							[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'      )
		lowerCamelCase_							:		Union[str, Any]							       =							', '.join(_parent_classes      )
		for idx, line in enumerate(snake_case__      ):
			# 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      ):
					lowerCamelCase_							:		str							       =							None  # noqa
				break
        # Add the new, one-line, class declaration for `test_class`
		lowerCamelCase_							:		List[Any]							       =							f"class {test_class.__name__}({parent_classes}):\n"

	# Add indentation
	lowerCamelCase_							:		int							       =							' ' * indent_level + line_to_add
	# Insert `pipeline_model_mapping` to `class_lines`.
	# (The line at `target_idx` should be kept by definition!)
	lowerCamelCase_							:		Optional[Any]							       =							class_lines[: target_idx + 1] + [line_to_add] + class_lines[target_idx + 1 :]
	# Remove the lines that are marked to be removed
	lowerCamelCase_							:		Union[str, 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)
	lowerCamelCase_							:		Any							       =							inspect.getsourcelines(inspect.getmodule(snake_case__      )      )[0]
	# Be careful with the 1-off between line numbers and array indices
	lowerCamelCase_							:		Dict							       =							module_lines[: class_start_line_no - 1] + class_lines + module_lines[class_end_line_no:]
	lowerCamelCase_							:		Any							       =							''.join(snake_case__      )

	lowerCamelCase_							:		List[str]							       =							inspect.getsourcefile(snake_case__      )
	with open(snake_case__						,       'w'						,       encoding='UTF-8'						,       newline='\n'      ) as fp:
		fp.write(snake_case__      )

	return line_to_add






def  snake_case (							A						,       A=False      )							->							List[str]:




	'''simple docstring'''


	lowerCamelCase_							:		Tuple							       =							find_test_class(snake_case__      )
	if test_class:
		add_pipeline_model_mapping(snake_case__						,       overwrite=snake_case__      )


if __name__ == "__main__":
							UpperCamelCase__		=						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`.',
							)
							UpperCamelCase__		=						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.')

							UpperCamelCase__		=						[]
							if args.test_file:
														UpperCamelCase__		=						[args.test_file]
							else:
														UpperCamelCase__		=						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)






import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class     __SCREAMING_SNAKE_CASE							(		lowerCamelCase       ,					unittest.TestCase  ):
					_lowerCamelCase		  =			KandinskyVaaPriorEmbaEmbPipeline
					_lowerCamelCase		  =			["""prompt""", """image"""]
					_lowerCamelCase		  =			["""prompt""", """image"""]
					_lowerCamelCase		  =			[
					    """num_images_per_prompt""",
					    """strength""",
					    """generator""",
					    """num_inference_steps""",
					    """latents""",
					    """negative_prompt""",
					    """guidance_scale""",
					    """output_type""",
					    """return_dict""",
					]
					_lowerCamelCase		  =			False

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						return 32

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						return 32

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						return self.time_input_dim

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						return self.time_input_dim * 4

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						return 100

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		Dict							       =							CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )
						return tokenizer

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						torch.manual_seed(0 )
						lowerCamelCase_							:		Dict							       =							CLIPTextConfig(
						    bos_token_id=0			,	eos_token_id=2			,	hidden_size=self.text_embedder_hidden_size			,	projection_dim=self.text_embedder_hidden_size			,	intermediate_size=37			,	layer_norm_eps=1E-05			,	num_attention_heads=4			,	num_hidden_layers=5			,	pad_token_id=1			,	vocab_size=1_000			,	)
						return CLIPTextModelWithProjection(__lowercase )

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						torch.manual_seed(0 )

						lowerCamelCase_							:		int							       =							{
						    'num_attention_heads': 2,
						    'attention_head_dim': 12,
						    'embedding_dim': self.text_embedder_hidden_size,
						    'num_layers': 1,
						}

						lowerCamelCase_							:		str							       =							PriorTransformer(**__lowercase )
						# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
						lowerCamelCase_							:		Dict							       =							nn.Parameter(torch.ones(model.clip_std.shape ) )
						return model

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						torch.manual_seed(0 )
						lowerCamelCase_							:		str							       =							CLIPVisionConfig(
						    hidden_size=self.text_embedder_hidden_size			,	image_size=224			,	projection_dim=self.text_embedder_hidden_size			,	intermediate_size=37			,	num_attention_heads=4			,	num_channels=3			,	num_hidden_layers=5			,	patch_size=14			,	)

						lowerCamelCase_							:		List[str]							       =							CLIPVisionModelWithProjection(__lowercase )
						return model

					@property
					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		int							       =							CLIPImageProcessor(
						    crop_size=224			,	do_center_crop=__lowercase			,	do_normalize=__lowercase			,	do_resize=__lowercase			,	image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]			,	image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]			,	resample=3			,	size=224			,	)

						return image_processor

					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		List[Any]							       =							self.dummy_prior
						lowerCamelCase_							:		str							       =							self.dummy_image_encoder
						lowerCamelCase_							:		Tuple							       =							self.dummy_text_encoder
						lowerCamelCase_							:		str							       =							self.dummy_tokenizer
						lowerCamelCase_							:		int							       =							self.dummy_image_processor

						lowerCamelCase_							:		Dict							       =							UnCLIPScheduler(
						    variance_type='fixed_small_log'			,	prediction_type='sample'			,	num_train_timesteps=1_000			,	clip_sample=__lowercase			,	clip_sample_range=10.0			,	)

						lowerCamelCase_							:		Dict							       =							{
						    'prior': prior,
						    'image_encoder': image_encoder,
						    'text_encoder': text_encoder,
						    'tokenizer': tokenizer,
						    'scheduler': scheduler,
						    'image_processor': image_processor,
						}

						return components

					def      lowercase_							(    self			,	__lowercase			,	__lowercase=0 ):







						'''simple docstring'''




						if str(__lowercase ).startswith('mps' ):
							lowerCamelCase_							:		Union[str, Any]							       =							torch.manual_seed(__lowercase )
						else:
							lowerCamelCase_							:		Optional[Any]							       =							torch.Generator(device=__lowercase ).manual_seed(__lowercase )

						lowerCamelCase_							:		Optional[int]							       =							floats_tensor((1, 3, 64, 64)			,	rng=random.Random(__lowercase ) ).to(__lowercase )
						lowerCamelCase_							:		Any							       =							image.cpu().permute(0			,	2			,	3			,	1 )[0]
						lowerCamelCase_							:		List[Any]							       =							Image.fromarray(np.uinta(__lowercase ) ).convert('RGB' ).resize((256, 256) )

						lowerCamelCase_							:		Tuple							       =							{
						    'prompt': 'horse',
						    'image': init_image,
						    'strength': 0.5,
						    'generator': generator,
						    'guidance_scale': 4.0,
						    'num_inference_steps': 2,
						    'output_type': 'np',
						}
						return inputs

					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		str							       =							'cpu'

						lowerCamelCase_							:		Union[str, Any]							       =							self.get_dummy_components()

						lowerCamelCase_							:		str							       =							self.pipeline_class(**__lowercase )
						lowerCamelCase_							:		Optional[Any]							       =							pipe.to(__lowercase )

						pipe.set_progress_bar_config(disable=__lowercase )

						lowerCamelCase_							:		List[str]							       =							pipe(**self.get_dummy_inputs(__lowercase ) )
						lowerCamelCase_							:		Union[str, Any]							       =							output.image_embeds

						lowerCamelCase_							:		List[str]							       =							pipe(
						    **self.get_dummy_inputs(__lowercase )			,	return_dict=__lowercase			,	)[0]

						lowerCamelCase_							:		List[Any]							       =							image[0, -10:]
						lowerCamelCase_							:		List[Any]							       =							image_from_tuple[0, -10:]

						assert image.shape == (1, 32)

						lowerCamelCase_							:		Any							       =							np.array(
						    [
						        0.1_07_12_84,
						        1.3_33_02_71,
						        0.61_26_02_23,
						        -0.6_69_10_65,
						        -0.3_84_68_52,
						        -1.0_30_36_61,
						        0.22_71_61_11,
						        0.03_34_89_01,
						        0.30_04_06_75,
						        -0.24_80_50_29,
						    ] )

						assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
						assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2

					@skip_mps
					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		int							       =							torch_device == 'cpu'
						lowerCamelCase_							:		Union[str, Any]							       =							True
						lowerCamelCase_							:		str							       =							False

						self._test_inference_batch_single_identical(
						    test_max_difference=__lowercase			,	relax_max_difference=__lowercase			,	test_mean_pixel_difference=__lowercase			,	)





					@skip_mps
					def      lowercase_							(    self ):







						'''simple docstring'''




						lowerCamelCase_							:		Optional[Any]							       =							torch_device == 'cpu'
						lowerCamelCase_							:		Optional[Any]							       =							False

						self._test_attention_slicing_forward_pass(
						    test_max_difference=__lowercase			,	test_mean_pixel_difference=__lowercase			,	)
