






'''simple docstring'''







import gc
import random
import unittest

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

from diffusers import AutoencoderKL, CycleDiffusionPipeline, DDIMScheduler, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class _lowercase     (    _lowercase    ,				_lowercase    ,				unittest.TestCase):
							a    				=	CycleDiffusionPipeline
							a    				=	TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {
							    """negative_prompt""",
							    """height""",
							    """width""",
							    """negative_prompt_embeds""",
							}
							a    				=	PipelineTesterMixin.required_optional_params - {"""latents"""}
							a    				=	TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""source_prompt"""})
							a    				=	IMAGE_TO_IMAGE_IMAGE_PARAMS
							a    				=	IMAGE_TO_IMAGE_IMAGE_PARAMS




							def 		lowerCamelCase_    (							self:    List[str]					):
														torch.manual_seed(0					)
														lowerCamelCase__ :     int	  =	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      ,							)
														lowerCamelCase__ :     Any	  =	DDIMScheduler(
														    beta_start=0.00_085      ,							beta_end=0.012      ,							beta_schedule="""scaled_linear"""      ,							num_train_timesteps=1_000      ,							clip_sample=__UpperCamelCase      ,							set_alpha_to_one=__UpperCamelCase      ,							)
														torch.manual_seed(0					)
														lowerCamelCase__ :     Optional[int]	  =	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					)
														lowerCamelCase__ :     Optional[int]	  =	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=1_000      ,							)
														lowerCamelCase__ :     Optional[int]	  =	CLIPTextModel(__UpperCamelCase					)
														lowerCamelCase__ :     Dict	  =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""					)

														lowerCamelCase__ :     Dict	  =	{
														    """unet""": unet,
														    """scheduler""": scheduler,
														    """vae""": vae,
														    """text_encoder""": text_encoder,
														    """tokenizer""": tokenizer,
														    """safety_checker""": None,
														    """feature_extractor""": None,
														}
														return components




							def 		lowerCamelCase_    (							self:    Tuple      ,							UpperCamelCase__:    Union[str, Any]      ,							UpperCamelCase__:    int=0					):
														lowerCamelCase__ :     Tuple	  =	floats_tensor((1, 3, 32, 32)      ,							rng=random.Random(__UpperCamelCase					)					).to(__UpperCamelCase					)
														lowerCamelCase__ :     Optional[int]	  =	image / 2 + 0.5
														if str(__UpperCamelCase					).startswith("""mps"""					):
																					lowerCamelCase__ :     Any	  =	torch.manual_seed(__UpperCamelCase					)
														else:
																					lowerCamelCase__ :     int	  =	torch.Generator(device=__UpperCamelCase					).manual_seed(__UpperCamelCase					)
														lowerCamelCase__ :     List[Any]	  =	{
														    """prompt""": """An astronaut riding an elephant""",
														    """source_prompt""": """An astronaut riding a horse""",
														    """image""": image,
														    """generator""": generator,
														    """num_inference_steps""": 2,
														    """eta""": 0.1,
														    """strength""": 0.8,
														    """guidance_scale""": 3,
														    """source_guidance_scale""": 1,
														    """output_type""": """numpy""",
														}
														return inputs




							def 		lowerCamelCase_    (							self:    Tuple					):
														lowerCamelCase__ :     Optional[int]	  =	"""cpu"""  # ensure determinism for the device-dependent torch.Generator

														lowerCamelCase__ :     str	  =	self.get_dummy_components()
														lowerCamelCase__ :     Dict	  =	CycleDiffusionPipeline(**__UpperCamelCase					)
														lowerCamelCase__ :     Union[str, Any]	  =	pipe.to(__UpperCamelCase					)
														pipe.set_progress_bar_config(disable=__UpperCamelCase					)

														lowerCamelCase__ :     Tuple	  =	self.get_dummy_inputs(__UpperCamelCase					)
														lowerCamelCase__ :     Union[str, Any]	  =	pipe(**__UpperCamelCase					)
														lowerCamelCase__ :     Tuple	  =	output.images

														lowerCamelCase__ :     Optional[int]	  =	images[0, -3:, -3:, -1]

														assert images.shape == (1, 32, 32, 3)
														lowerCamelCase__ :     Optional[Any]	  =	np.array([0.4_459, 0.4_943, 0.4_544, 0.6_643, 0.5_474, 0.4_327, 0.5_701, 0.5_959, 0.5_179]					)

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




							@unittest.skipIf(torch_device != """cuda"""      ,							"""This test requires a GPU"""					)
							def 		lowerCamelCase_    (							self:    List[Any]					):
														lowerCamelCase__ :     List[str]	  =	self.get_dummy_components()
														for name, module in components.items():
																					if hasattr(__UpperCamelCase      ,							"""half"""					):
																												lowerCamelCase__ :     int	  =	module.half()
														lowerCamelCase__ :     Dict	  =	CycleDiffusionPipeline(**__UpperCamelCase					)
														lowerCamelCase__ :     List[Any]	  =	pipe.to(__UpperCamelCase					)
														pipe.set_progress_bar_config(disable=__UpperCamelCase					)

														lowerCamelCase__ :     Dict	  =	self.get_dummy_inputs(__UpperCamelCase					)
														lowerCamelCase__ :     Optional[Any]	  =	pipe(**__UpperCamelCase					)
														lowerCamelCase__ :     int	  =	output.images

														lowerCamelCase__ :     Optional[int]	  =	images[0, -3:, -3:, -1]

														assert images.shape == (1, 32, 32, 3)
														lowerCamelCase__ :     int	  =	np.array([0.3_506, 0.4_543, 0.446, 0.4_575, 0.5_195, 0.4_155, 0.5_273, 0.518, 0.4_116]					)

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




							@skip_mps
							def 		lowerCamelCase_    (							self:    Any					):
														return super().test_save_load_local()




							@unittest.skip("""non-deterministic pipeline"""					)
							def 		lowerCamelCase_    (							self:    List[str]					):
														return super().test_inference_batch_single_identical()




							@skip_mps
							def 		lowerCamelCase_    (							self:    str					):
														return super().test_dict_tuple_outputs_equivalent()




							@skip_mps
							def 		lowerCamelCase_    (							self:    Tuple					):
														return super().test_save_load_optional_components()




							@skip_mps
							def 		lowerCamelCase_    (							self:    Any					):
														return super().test_attention_slicing_forward_pass()



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




							def 		lowerCamelCase_    (							self:    Dict					):
														# clean up the VRAM after each test
														super().tearDown()
														gc.collect()
														torch.cuda.empty_cache()




							def 		lowerCamelCase_    (							self:    Optional[int]					):
														lowerCamelCase__ :     Dict	  =	load_image(
														    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
														    """/cycle-diffusion/black_colored_car.png"""					)
														lowerCamelCase__ :     List[str]	  =	load_numpy(
														    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car_fp16.npy"""					)
														lowerCamelCase__ :     Any	  =	init_image.resize((512, 512)					)

														lowerCamelCase__ :     List[str]	  =	"""CompVis/stable-diffusion-v1-4"""
														lowerCamelCase__ :     Union[str, Any]	  =	DDIMScheduler.from_pretrained(__UpperCamelCase      ,							subfolder="""scheduler"""					)
														lowerCamelCase__ :     Optional[Any]	  =	CycleDiffusionPipeline.from_pretrained(
														    __UpperCamelCase      ,							scheduler=__UpperCamelCase      ,							safety_checker=__UpperCamelCase      ,							torch_dtype=torch.floataa      ,							revision="""fp16"""					)

														pipe.to(__UpperCamelCase					)
														pipe.set_progress_bar_config(disable=__UpperCamelCase					)
														pipe.enable_attention_slicing()

														lowerCamelCase__ :     int	  =	"""A black colored car"""
														lowerCamelCase__ :     Any	  =	"""A blue colored car"""

														lowerCamelCase__ :     List[str]	  =	torch.manual_seed(0					)
														lowerCamelCase__ :     str	  =	pipe(
														    prompt=__UpperCamelCase      ,							source_prompt=__UpperCamelCase      ,							image=__UpperCamelCase      ,							num_inference_steps=100      ,							eta=0.1      ,							strength=0.85      ,							guidance_scale=3      ,							source_guidance_scale=1      ,							generator=__UpperCamelCase      ,							output_type="""np"""      ,							)
														lowerCamelCase__ :     str	  =	output.images

														# the values aren't exactly equal, but the images look the same visually
														assert np.abs(image - expected_image					).max() < 5e-1




							def 		lowerCamelCase_    (							self:    int					):
														lowerCamelCase__ :     Dict	  =	load_image(
														    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
														    """/cycle-diffusion/black_colored_car.png"""					)
														lowerCamelCase__ :     Union[str, Any]	  =	load_numpy(
														    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/cycle-diffusion/blue_colored_car.npy"""					)
														lowerCamelCase__ :     Any	  =	init_image.resize((512, 512)					)

														lowerCamelCase__ :     Dict	  =	"""CompVis/stable-diffusion-v1-4"""
														lowerCamelCase__ :     Optional[int]	  =	DDIMScheduler.from_pretrained(__UpperCamelCase      ,							subfolder="""scheduler"""					)
														lowerCamelCase__ :     List[Any]	  =	CycleDiffusionPipeline.from_pretrained(__UpperCamelCase      ,							scheduler=__UpperCamelCase      ,							safety_checker=__UpperCamelCase					)

														pipe.to(__UpperCamelCase					)
														pipe.set_progress_bar_config(disable=__UpperCamelCase					)
														pipe.enable_attention_slicing()

														lowerCamelCase__ :     Any	  =	"""A black colored car"""
														lowerCamelCase__ :     Union[str, Any]	  =	"""A blue colored car"""

														lowerCamelCase__ :     int	  =	torch.manual_seed(0					)
														lowerCamelCase__ :     Union[str, Any]	  =	pipe(
														    prompt=__UpperCamelCase      ,							source_prompt=__UpperCamelCase      ,							image=__UpperCamelCase      ,							num_inference_steps=100      ,							eta=0.1      ,							strength=0.85      ,							guidance_scale=3      ,							source_guidance_scale=1      ,							generator=__UpperCamelCase      ,							output_type="""np"""      ,							)
														lowerCamelCase__ :     List[Any]	  =	output.images

														assert np.abs(image - expected_image					).max() < 2e-2









'''simple docstring'''







import json
import os
import shutil
import tempfile
import unittest

import numpy as np
import pytest

from transformers import BertTokenizer, BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES
from transformers.testing_utils import require_vision
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_vision_available


if is_vision_available():
			from PIL import Image

			from transformers import ChineseCLIPImageProcessor, ChineseCLIPProcessor

@require_vision
class _lowercase     (    unittest.TestCase		):




							def 		lowerCamelCase_    (							self:    Union[str, Any]					):
														lowerCamelCase__ :     Any	  =	tempfile.mkdtemp()

														lowerCamelCase__ :     Any	  =	[
														    """[UNK]""",
														    """[CLS]""",
														    """[SEP]""",
														    """[PAD]""",
														    """[MASK]""",
														    """的""",
														    """价""",
														    """格""",
														    """是""",
														    """15""",
														    """便""",
														    """alex""",
														    """##andra""",
														    """，""",
														    """。""",
														    """-""",
														    """t""",
														    """shirt""",
														]
														lowerCamelCase__ :     Optional[int]	  =	os.path.join(self.tmpdirname      ,							VOCAB_FILES_NAMES["""vocab_file"""]					)
														with open(self.vocab_file      ,							"""w"""      ,							encoding="""utf-8"""					) as vocab_writer:
																					vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]					)					)

														lowerCamelCase__ :     Union[str, Any]	  =	{
														    """do_resize""": True,
														    """size""": {"""height""": 224, """width""": 224},
														    """do_center_crop""": True,
														    """crop_size""": {"""height""": 18, """width""": 18},
														    """do_normalize""": True,
														    """image_mean""": [0.48_145_466, 0.4_578_275, 0.40_821_073],
														    """image_std""": [0.26_862_954, 0.26_130_258, 0.27_577_711],
														    """do_convert_rgb""": True,
														}
														lowerCamelCase__ :     Optional[int]	  =	os.path.join(self.tmpdirname      ,							UpperCamelCase__					)
														with open(self.image_processor_file      ,							"""w"""      ,							encoding="""utf-8"""					) as fp:
																					json.dump(UpperCamelCase__      ,							UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    List[Any]      ,							**UpperCamelCase__:    Optional[int]					):
														return BertTokenizer.from_pretrained(self.tmpdirname      ,							**UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Any      ,							**UpperCamelCase__:    List[str]					):
														return BertTokenizerFast.from_pretrained(self.tmpdirname      ,							**UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    str      ,							**UpperCamelCase__:    int					):
														return ChineseCLIPImageProcessor.from_pretrained(self.tmpdirname      ,							**UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Optional[int]					):
														shutil.rmtree(self.tmpdirname					)




							def 		lowerCamelCase_    (							self:    List[str]					):
														lowerCamelCase__ :     int	  =	[np.random.randint(255      ,							size=(3, 30, 400)      ,							dtype=np.uinta					)]

														lowerCamelCase__ :     List[str]	  =	[Image.fromarray(np.moveaxis(UpperCamelCase__      ,							0      ,							-1					)					) for x in image_inputs]

														return image_inputs




							def 		lowerCamelCase_    (							self:    List[str]					):
														lowerCamelCase__ :     Tuple	  =	self.get_tokenizer()
														lowerCamelCase__ :     Any	  =	self.get_rust_tokenizer()
														lowerCamelCase__ :     str	  =	self.get_image_processor()

														lowerCamelCase__ :     str	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)
														processor_slow.save_pretrained(self.tmpdirname					)
														lowerCamelCase__ :     List[Any]	  =	ChineseCLIPProcessor.from_pretrained(self.tmpdirname      ,							use_fast=UpperCamelCase__					)

														lowerCamelCase__ :     Any	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)
														processor_fast.save_pretrained(self.tmpdirname					)
														lowerCamelCase__ :     List[Any]	  =	ChineseCLIPProcessor.from_pretrained(self.tmpdirname					)

														self.assertEqual(processor_slow.tokenizer.get_vocab()      ,							tokenizer_slow.get_vocab()					)
														self.assertEqual(processor_fast.tokenizer.get_vocab()      ,							tokenizer_fast.get_vocab()					)
														self.assertEqual(tokenizer_slow.get_vocab()      ,							tokenizer_fast.get_vocab()					)
														self.assertIsInstance(processor_slow.tokenizer      ,							UpperCamelCase__					)
														self.assertIsInstance(processor_fast.tokenizer      ,							UpperCamelCase__					)

														self.assertEqual(processor_slow.image_processor.to_json_string()      ,							image_processor.to_json_string()					)
														self.assertEqual(processor_fast.image_processor.to_json_string()      ,							image_processor.to_json_string()					)
														self.assertIsInstance(processor_slow.image_processor      ,							UpperCamelCase__					)
														self.assertIsInstance(processor_fast.image_processor      ,							UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Optional[int]					):
														lowerCamelCase__ :     Optional[int]	  =	ChineseCLIPProcessor(tokenizer=self.get_tokenizer()      ,							image_processor=self.get_image_processor()					)
														processor.save_pretrained(self.tmpdirname					)

														lowerCamelCase__ :     str	  =	self.get_tokenizer(cls_token="""(CLS)"""      ,							sep_token="""(SEP)"""					)
														lowerCamelCase__ :     Optional[int]	  =	self.get_image_processor(do_normalize=UpperCamelCase__					)

														lowerCamelCase__ :     Optional[int]	  =	ChineseCLIPProcessor.from_pretrained(
														    self.tmpdirname      ,							cls_token="""(CLS)"""      ,							sep_token="""(SEP)"""      ,							do_normalize=UpperCamelCase__					)

														self.assertEqual(processor.tokenizer.get_vocab()      ,							tokenizer_add_kwargs.get_vocab()					)
														self.assertIsInstance(processor.tokenizer      ,							UpperCamelCase__					)

														self.assertEqual(processor.image_processor.to_json_string()      ,							image_processor_add_kwargs.to_json_string()					)
														self.assertIsInstance(processor.image_processor      ,							UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Tuple					):
														lowerCamelCase__ :     Optional[Any]	  =	self.get_image_processor()
														lowerCamelCase__ :     Optional[int]	  =	self.get_tokenizer()

														lowerCamelCase__ :     int	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)

														lowerCamelCase__ :     Tuple	  =	self.prepare_image_inputs()

														lowerCamelCase__ :     str	  =	image_processor(UpperCamelCase__      ,							return_tensors="""np"""					)
														lowerCamelCase__ :     Optional[int]	  =	processor(images=UpperCamelCase__      ,							return_tensors="""np"""					)

														for key in input_feat_extract.keys():
																					self.assertAlmostEqual(input_feat_extract[key].sum()      ,							input_processor[key].sum()      ,							delta=1e-2					)




							def 		lowerCamelCase_    (							self:    Tuple					):
														lowerCamelCase__ :     int	  =	self.get_image_processor()
														lowerCamelCase__ :     Optional[int]	  =	self.get_tokenizer()

														lowerCamelCase__ :     Union[str, Any]	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)

														lowerCamelCase__ :     Union[str, Any]	  =	"""Alexandra，T-shirt的价格是15便士。"""

														lowerCamelCase__ :     Optional[Any]	  =	processor(text=UpperCamelCase__					)

														lowerCamelCase__ :     Optional[Any]	  =	tokenizer(UpperCamelCase__					)

														for key in encoded_tok.keys():
																					self.assertListEqual(encoded_tok[key]      ,							encoded_processor[key]					)




							def 		lowerCamelCase_    (							self:    Optional[Any]					):
														lowerCamelCase__ :     Optional[int]	  =	self.get_image_processor()
														lowerCamelCase__ :     List[Any]	  =	self.get_tokenizer()

														lowerCamelCase__ :     Optional[Any]	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)

														lowerCamelCase__ :     Dict	  =	"""Alexandra，T-shirt的价格是15便士。"""
														lowerCamelCase__ :     Any	  =	self.prepare_image_inputs()

														lowerCamelCase__ :     Optional[int]	  =	processor(text=UpperCamelCase__      ,							images=UpperCamelCase__					)

														self.assertListEqual(list(inputs.keys()					)      ,							["""input_ids""", """token_type_ids""", """attention_mask""", """pixel_values"""]					)

														# test if it raises when no input is passed
														with pytest.raises(UpperCamelCase__					):
																					processor()




							def 		lowerCamelCase_    (							self:    Dict					):
														lowerCamelCase__ :     Dict	  =	self.get_image_processor()
														lowerCamelCase__ :     Any	  =	self.get_tokenizer()

														lowerCamelCase__ :     Union[str, Any]	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)

														lowerCamelCase__ :     str	  =	[[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

														lowerCamelCase__ :     Any	  =	processor.batch_decode(UpperCamelCase__					)
														lowerCamelCase__ :     int	  =	tokenizer.batch_decode(UpperCamelCase__					)

														self.assertListEqual(UpperCamelCase__      ,							UpperCamelCase__					)




							def 		lowerCamelCase_    (							self:    Optional[Any]					):
														lowerCamelCase__ :     Dict	  =	self.get_image_processor()
														lowerCamelCase__ :     int	  =	self.get_tokenizer()

														lowerCamelCase__ :     Optional[Any]	  =	ChineseCLIPProcessor(tokenizer=UpperCamelCase__      ,							image_processor=UpperCamelCase__					)

														lowerCamelCase__ :     Optional[Any]	  =	"""Alexandra，T-shirt的价格是15便士。"""
														lowerCamelCase__ :     Tuple	  =	self.prepare_image_inputs()

														lowerCamelCase__ :     str	  =	processor(text=UpperCamelCase__      ,							images=UpperCamelCase__					)

														self.assertListEqual(list(inputs.keys()					)      ,							processor.model_input_names					)

