
"""simple docstring"""




import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class 	lowerCAmelCase_						(a__ ,					unittest.TestCase  ):


				"""simple docstring"""



				__UpperCamelCase      :						str					       =   LDMTextToImagePipeline
				__UpperCamelCase      :						Dict					       =   TEXT_TO_IMAGE_PARAMS - {
				    '''negative_prompt''',
				    '''negative_prompt_embeds''',
				    '''cross_attention_kwargs''',
				    '''prompt_embeds''',
				}
				__UpperCamelCase      :						List[str]					       =   PipelineTesterMixin.required_optional_params - {
				    '''num_images_per_prompt''',
				    '''callback''',
				    '''callback_steps''',
				}
				__UpperCamelCase      :						Any					       =   TEXT_TO_IMAGE_BATCH_PARAMS
				__UpperCamelCase      :						Union[str, Any]					       =   False



				def 	__magic_name__    (self    )					->		List[str]:



											"""simple docstring"""




											torch.manual_seed(0    )
											SCREAMING_SNAKE_CASE__						:       Any           =   UNetaDConditionModel(
											    block_out_channels=(32, 64)   ,       layers_per_block=2   ,       sample_size=32   ,       in_channels=4   ,       out_channels=4   ,       down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")   ,       up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")   ,       cross_attention_dim=32   ,       )
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   DDIMScheduler(
											    beta_start=0.00085   ,       beta_end=0.012   ,       beta_schedule="""scaled_linear"""   ,       clip_sample=SCREAMING_SNAKE_CASE__   ,       set_alpha_to_one=SCREAMING_SNAKE_CASE__   ,       )
											torch.manual_seed(0    )
											SCREAMING_SNAKE_CASE__						:       List[str]           =   AutoencoderKL(
											    block_out_channels=(32, 64)   ,       in_channels=3   ,       out_channels=3   ,       down_block_types=("""DownEncoderBlock2D""", """DownEncoderBlock2D""")   ,       up_block_types=("""UpDecoderBlock2D""", """UpDecoderBlock2D""")   ,       latent_channels=4   ,       )
											torch.manual_seed(0    )
											SCREAMING_SNAKE_CASE__						:       List[str]           =   CLIPTextConfig(
											    bos_token_id=0   ,       eos_token_id=2   ,       hidden_size=32   ,       intermediate_size=37   ,       layer_norm_eps=1E-05   ,       num_attention_heads=4   ,       num_hidden_layers=5   ,       pad_token_id=1   ,       vocab_size=10_00   ,       )
											SCREAMING_SNAKE_CASE__						:       Dict           =   CLIPTextModel(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Any           =   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )

											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   {
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """vqvae""": vae,
											    """bert""": text_encoder,
											    """tokenizer""": tokenizer,
											}
											return components



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__=0    )					->		Optional[int]:



											"""simple docstring"""




											if str(SCREAMING_SNAKE_CASE__    ).startswith("""mps"""    ):
																		SCREAMING_SNAKE_CASE__						:       Optional[int]           =   torch.manual_seed(SCREAMING_SNAKE_CASE__    )
											else:
																		SCREAMING_SNAKE_CASE__						:       int           =   torch.Generator(device=SCREAMING_SNAKE_CASE__    ).manual_seed(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Tuple           =   {
											    """prompt""": """A painting of a squirrel eating a burger""",
											    """generator""": generator,
											    """num_inference_steps""": 2,
											    """guidance_scale""": 6.0,
											    """output_type""": """numpy""",
											}
											return inputs



				def 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       List[Any]           =   """cpu"""  # ensure determinism for the device-dependent torch.Generator

											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   self.get_dummy_components()
											SCREAMING_SNAKE_CASE__						:       str           =   LDMTextToImagePipeline(**SCREAMING_SNAKE_CASE__    )
											pipe.to(SCREAMING_SNAKE_CASE__    )
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       str           =   self.get_dummy_inputs(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Dict           =   pipe(**SCREAMING_SNAKE_CASE__    ).images
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   image[0, -3:, -3:, -1]

											assert image.shape == (1, 16, 16, 3)
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014]    )

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






@slow
@require_torch_gpu
class 	lowerCAmelCase_						(unittest.TestCase  ):


				"""simple docstring"""



				def 	__magic_name__    (self    )					->		str:



											"""simple docstring"""




											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__=torch.floataa   ,       SCREAMING_SNAKE_CASE__=0    )					->		List[str]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       List[str]           =   torch.manual_seed(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   np.random.RandomState(SCREAMING_SNAKE_CASE__    ).standard_normal((1, 4, 32, 32)    )
											SCREAMING_SNAKE_CASE__						:       Dict           =   torch.from_numpy(SCREAMING_SNAKE_CASE__    ).to(device=SCREAMING_SNAKE_CASE__   ,       dtype=SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Tuple           =   {
											    """prompt""": """A painting of a squirrel eating a burger""",
											    """latents""": latents,
											    """generator""": generator,
											    """num_inference_steps""": 3,
											    """guidance_scale""": 6.0,
											    """output_type""": """numpy""",
											}
											return inputs



				def 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""    ).to(SCREAMING_SNAKE_CASE__    )
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   self.get_inputs(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Dict           =   pipe(**SCREAMING_SNAKE_CASE__    ).images
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   image[0, -3:, -3:, -1].flatten()

											assert image.shape == (1, 2_56, 2_56, 3)
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878]    )
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   np.abs(expected_slice - image_slice    ).max()
											assert max_diff < 1E-3






@nightly
@require_torch_gpu
class 	lowerCAmelCase_						(unittest.TestCase  ):


				"""simple docstring"""



				def 	__magic_name__    (self    )					->		str:



											"""simple docstring"""




											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__=torch.floataa   ,       SCREAMING_SNAKE_CASE__=0    )					->		Union[str, Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Dict           =   torch.manual_seed(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Any           =   np.random.RandomState(SCREAMING_SNAKE_CASE__    ).standard_normal((1, 4, 32, 32)    )
											SCREAMING_SNAKE_CASE__						:       str           =   torch.from_numpy(SCREAMING_SNAKE_CASE__    ).to(device=SCREAMING_SNAKE_CASE__   ,       dtype=SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   {
											    """prompt""": """A painting of a squirrel eating a burger""",
											    """latents""": latents,
											    """generator""": generator,
											    """num_inference_steps""": 50,
											    """guidance_scale""": 6.0,
											    """output_type""": """numpy""",
											}
											return inputs



				def 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Any           =   LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""    ).to(SCREAMING_SNAKE_CASE__    )
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       Any           =   self.get_inputs(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   pipe(**SCREAMING_SNAKE_CASE__    ).images[0]

											SCREAMING_SNAKE_CASE__						:       str           =   load_numpy(
											    """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy"""    )
											SCREAMING_SNAKE_CASE__						:       Dict           =   np.abs(expected_image - image    ).max()
											assert max_diff < 1E-3






"""simple docstring"""




import logging
import os
import sys
from pathlib import Path
from unittest.mock import patch

from parameterized import parameterized
from run_eval import run_generate
from run_eval_search import run_search

from transformers.testing_utils import CaptureStdout, TestCasePlus, slow
from utils import ROUGE_KEYS


logging.basicConfig(level=logging.DEBUG)
UpperCAmelCase__      :    List[Any]    							= logging.getLogger()

def lowercase_  (   _snake_case   ,_snake_case						):
							SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   """\n""".join(_snake_case						)
							Path(_snake_case						).open("""w"""						).writelines(_snake_case						)


UpperCAmelCase__      :    Union[str, Any]    							= 'patrickvonplaten/t5-tiny-random'
UpperCAmelCase__      :    Optional[int]    							= 'sshleifer/bart-tiny-random'
UpperCAmelCase__      :    Dict    							= 'sshleifer/tiny-mbart'

UpperCAmelCase__      :    int    							= logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)
logging.disable(logging.CRITICAL)  # remove noisy download output from tracebacks



class 	lowerCAmelCase_						(a__  ):


				"""simple docstring"""



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__    )					->		str:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   Path(self.get_auto_remove_tmp_dir()    ) / """utest_input.source"""
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   input_file_name.parent / """utest_output.txt"""
											assert not output_file_name.exists()
											SCREAMING_SNAKE_CASE__						:       str           =   [""" New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County."""]
											_dump_articles(SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       Any           =   str(Path(self.get_auto_remove_tmp_dir()    ) / """scores.json"""    )
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   """translation_en_to_de""" if model == T5_TINY else """summarization"""
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   F'''
            run_eval_search.py
            {model}
            {input_file_name}
            {output_file_name}
            --score_path {score_path}
            --task {task}
            --num_beams 2
            --length_penalty 2.0
            '''.split()

											with patch.object(SCREAMING_SNAKE_CASE__   ,       """argv"""   ,       SCREAMING_SNAKE_CASE__    ):
																		run_generate()
																		assert Path(SCREAMING_SNAKE_CASE__    ).exists()
																		# os.remove(Path(output_file_name))



				def 	__magic_name__    (self    )					->		Dict:



											"""simple docstring"""




											self.run_eval_tester(SCREAMING_SNAKE_CASE__    )



				@parameterized.expand([BART_TINY, MBART_TINY]    )
				@slow
				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__    )					->		Dict:



											"""simple docstring"""




											self.run_eval_tester(SCREAMING_SNAKE_CASE__    )



				@parameterized.expand([T5_TINY, MBART_TINY]    )
				@slow
				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__    )					->		Dict:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       List[Any]           =   Path(self.get_auto_remove_tmp_dir()    ) / """utest_input.source"""
											SCREAMING_SNAKE_CASE__						:       int           =   input_file_name.parent / """utest_output.txt"""
											assert not output_file_name.exists()

											SCREAMING_SNAKE_CASE__						:       Any           =   {
											    """en""": ["""Machine learning is great, isn't it?""", """I like to eat bananas""", """Tomorrow is another great day!"""],
											    """de""": [
											        """Maschinelles Lernen ist großartig, oder?""",
											        """Ich esse gerne Bananen""",
											        """Morgen ist wieder ein toller Tag!""",
											    ],
											}

											SCREAMING_SNAKE_CASE__						:       List[str]           =   Path(self.get_auto_remove_tmp_dir()    )
											SCREAMING_SNAKE_CASE__						:       Tuple           =   str(tmp_dir / """scores.json"""    )
											SCREAMING_SNAKE_CASE__						:       Tuple           =   str(tmp_dir / """val.target"""    )
											_dump_articles(SCREAMING_SNAKE_CASE__   ,       text["""en"""]    )
											_dump_articles(SCREAMING_SNAKE_CASE__   ,       text["""de"""]    )
											SCREAMING_SNAKE_CASE__						:       str           =   """translation_en_to_de""" if model == T5_TINY else """summarization"""
											SCREAMING_SNAKE_CASE__						:       List[Any]           =   F'''
            run_eval_search.py
            {model}
            {str(SCREAMING_SNAKE_CASE__    )}
            {str(SCREAMING_SNAKE_CASE__    )}
            --score_path {score_path}
            --reference_path {reference_path}
            --task {task}
            '''.split()
											testargs.extend(["""--search""", """num_beams=1:2 length_penalty=0.9:1.0"""]    )

											with patch.object(SCREAMING_SNAKE_CASE__   ,       """argv"""   ,       SCREAMING_SNAKE_CASE__    ):
																		with CaptureStdout() as cs:
																									run_search()
																		SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   [""" num_beams | length_penalty""", model, """Best score args"""]
																		SCREAMING_SNAKE_CASE__						:       Any           =   ["""Info"""]
																		if "translation" in task:
																									expected_strings.append("""bleu"""    )
																		else:
																									expected_strings.extend(SCREAMING_SNAKE_CASE__    )
																		for w in expected_strings:
																									assert w in cs.out
																		for w in un_expected_strings:
																									assert w not in cs.out
																		assert Path(SCREAMING_SNAKE_CASE__    ).exists()
																		os.remove(Path(SCREAMING_SNAKE_CASE__    )    )




