



"""simple docstring"""







import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()

class 			_a     (   SCREAMING_SNAKE_CASE__    ,  unittest.TestCase):
			__magic_name__    				=    KandinskyPipeline
			__magic_name__    				=    [
			    """prompt""",
			    """image_embeds""",
			    """negative_image_embeds""",
			]
			__magic_name__    				=    ["""prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds"""]
			__magic_name__    				=    [
			    """generator""",
			    """height""",
			    """width""",
			    """latents""",
			    """guidance_scale""",
			    """negative_prompt""",
			    """num_inference_steps""",
			    """return_dict""",
			    """guidance_scale""",
			    """num_images_per_prompt""",
			    """output_type""",
			    """return_dict""",
			]
			__magic_name__    				=    False



			@property
			def 							__lowercase				( self       :							Union[str, Any]		)       ->				List[Any]:
									return 32



			@property
			def 							__lowercase				( self       :							List[Any]		)       ->				Tuple:
									return 32



			@property
			def 							__lowercase				( self       :							int		)       ->				List[Any]:
									return self.time_input_dim



			@property
			def 							__lowercase				( self       :							Optional[int]		)       ->				Any:
									return self.time_input_dim * 4



			@property
			def 							__lowercase				( self       :							Tuple		)       ->				int:
									return 100



			@property
			def 							__lowercase				( self       :							Optional[int]		)       ->				Optional[int]:
									snake_case      : Optional[int]							=   XLMRobertaTokenizerFast.from_pretrained("YiYiXu/tiny-random-mclip-base"		)
									return tokenizer



			@property
			def 							__lowercase				( self       :							Optional[Any]		)       ->				List[Any]:
									torch.manual_seed(0		)
									snake_case      : List[Any]							=   MCLIPConfig(
									    numDims=self.cross_attention_dim      ,  transformerDimensions=self.text_embedder_hidden_size      ,  hidden_size=self.text_embedder_hidden_size      ,  intermediate_size=37      ,  num_attention_heads=4      ,  num_hidden_layers=5      ,  vocab_size=1005      ,  )

									snake_case      : Optional[Any]							=   MultilingualCLIP(_lowercase		)
									snake_case      : int							=   text_encoder.eval()

									return text_encoder



			@property
			def 							__lowercase				( self       :							Tuple		)       ->				List[str]:
									torch.manual_seed(0		)

									snake_case      : Any							=   {
									    "in_channels": 4,
									    # Out channels is double in channels because predicts mean and variance
									    "out_channels": 8,
									    "addition_embed_type": "text_image",
									    "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
									    "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
									    "mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
									    "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
									    "layers_per_block": 1,
									    "encoder_hid_dim": self.text_embedder_hidden_size,
									    "encoder_hid_dim_type": "text_image_proj",
									    "cross_attention_dim": self.cross_attention_dim,
									    "attention_head_dim": 4,
									    "resnet_time_scale_shift": "scale_shift",
									    "class_embed_type": None,
									}

									snake_case      : Any							=   UNetaDConditionModel(**_lowercase		)
									return model



			@property
			def 							__lowercase				( self       :							Any		)       ->				Union[str, Any]:
									return {
									    "block_out_channels": [32, 64],
									    "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
									    "in_channels": 3,
									    "latent_channels": 4,
									    "layers_per_block": 1,
									    "norm_num_groups": 8,
									    "norm_type": "spatial",
									    "num_vq_embeddings": 12,
									    "out_channels": 3,
									    "up_block_types": [
									        "AttnUpDecoderBlock2D",
									        "UpDecoderBlock2D",
									    ],
									    "vq_embed_dim": 4,
									}



			@property
			def 							__lowercase				( self       :							Tuple		)       ->				List[Any]:
									torch.manual_seed(0		)
									snake_case      : List[str]							=   VQModel(**self.dummy_movq_kwargs		)
									return model



			def 							__lowercase				( self       :							List[Any]		)       ->				List[str]:
									snake_case      : List[str]							=   self.dummy_text_encoder
									snake_case      : List[str]							=   self.dummy_tokenizer
									snake_case      : Union[str, Any]							=   self.dummy_unet
									snake_case      : Any							=   self.dummy_movq

									snake_case      : List[str]							=   DDIMScheduler(
									    num_train_timesteps=1000      ,  beta_schedule="linear"      ,  beta_start=0.00085      ,  beta_end=0.012      ,  clip_sample=_lowercase      ,  set_alpha_to_one=_lowercase      ,  steps_offset=1      ,  prediction_type="epsilon"      ,  thresholding=_lowercase      ,  )

									snake_case      : Dict							=   {
									    "text_encoder": text_encoder,
									    "tokenizer": tokenizer,
									    "unet": unet,
									    "scheduler": scheduler,
									    "movq": movq,
									}
									return components



			def 							__lowercase				( self       :							Union[str, Any]      ,  _lowercase       :							Dict      ,  _lowercase       :							str=0		)       ->				str:
									snake_case      : str							=   floats_tensor((1, self.cross_attention_dim)      ,  rng=random.Random(_lowercase		)		).to(_lowercase		)
									snake_case      : int							=   floats_tensor((1, self.cross_attention_dim)      ,  rng=random.Random(seed + 1		)		).to(_lowercase		)
									if str(_lowercase		).startswith("mps"		):
															snake_case      : Any							=   torch.manual_seed(_lowercase		)
									else:
															snake_case      : Tuple							=   torch.Generator(device=_lowercase		).manual_seed(_lowercase		)
									snake_case      : Any							=   {
									    "prompt": "horse",
									    "image_embeds": image_embeds,
									    "negative_image_embeds": negative_image_embeds,
									    "generator": generator,
									    "height": 64,
									    "width": 64,
									    "guidance_scale": 4.0,
									    "num_inference_steps": 2,
									    "output_type": "np",
									}
									return inputs



			def 							__lowercase				( self       :							Dict		)       ->				Union[str, Any]:
									snake_case      : Union[str, Any]							=   "cpu"

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

									snake_case      : Dict							=   self.pipeline_class(**_lowercase		)
									snake_case      : List[str]							=   pipe.to(_lowercase		)

									pipe.set_progress_bar_config(disable=_lowercase		)

									snake_case      : int							=   pipe(**self.get_dummy_inputs(_lowercase		)		)
									snake_case      : Tuple							=   output.images

									snake_case      : int							=   pipe(
									    **self.get_dummy_inputs(_lowercase		)      ,  return_dict=_lowercase      ,  )[0]

									snake_case      : Optional[int]							=   image[0, -3:, -3:, -1]
									snake_case      : int							=   image_from_tuple[0, -3:, -3:, -1]

									assert image.shape == (1, 64, 64, 3)

									snake_case      : Union[str, Any]							=   np.array(
									    [0.328663, 1.0, 0.23216873, 1.0, 0.92717564, 0.4639046, 0.96894777, 0.31713378, 0.6293953]		)

									assert (
									    np.abs(image_slice.flatten() - expected_slice		).max() < 1E-2
									), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
									assert (
									    np.abs(image_from_tuple_slice.flatten() - expected_slice		).max() < 1E-2
									), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''



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



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



			def 							__lowercase				( self       :							Optional[int]		)       ->				Dict:
									snake_case      : Optional[Any]							=   load_numpy(
									    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
									    "/kandinsky/kandinsky_text2img_cat_fp16.npy"		)

									snake_case      : Optional[Any]							=   KandinskyPriorPipeline.from_pretrained(
									    "kandinsky-community/kandinsky-2-1-prior"      ,  torch_dtype=torch.floataa		)
									pipe_prior.to(_lowercase		)

									snake_case      : Union[str, Any]							=   KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1"      ,  torch_dtype=torch.floataa		)
									snake_case      : Optional[int]							=   pipeline.to(_lowercase		)
									pipeline.set_progress_bar_config(disable=_lowercase		)

									snake_case      : Dict							=   "red cat, 4k photo"

									snake_case      : Dict							=   torch.Generator(device="cuda"		).manual_seed(0		)
									snake_case						, snake_case      : Optional[int]							=   pipe_prior(
									    _lowercase      ,  generator=_lowercase      ,  num_inference_steps=5      ,  negative_prompt=""      ,  ).to_tuple()

									snake_case      : Dict							=   torch.Generator(device="cuda"		).manual_seed(0		)
									snake_case      : List[Any]							=   pipeline(
									    _lowercase      ,  image_embeds=_lowercase      ,  negative_image_embeds=_lowercase      ,  generator=_lowercase      ,  num_inference_steps=100      ,  output_type="np"      ,  )

									snake_case      : Dict							=   output.images[0]

									assert image.shape == (512, 512, 3)

									assert_mean_pixel_difference(_lowercase      ,  _lowercase		)








"""simple docstring"""







import unittest

from cer import CER


A    =	CER()

class 			_a     (   unittest.TestCase):



			def 							__lowercase				( self       :							Optional[Any]		)       ->				Tuple:
									snake_case      : Union[str, Any]							=   ["White House"]
									snake_case      : Tuple							=   ["white house"]
									# S = 2, D = 0, I = 0, N = 11, CER = 2 / 11
									snake_case      : int							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.1818181818		) < 1E-6		)



			def 							__lowercase				( self       :							Optional[Any]		)       ->				Dict:
									snake_case      : Tuple							=   ["were wolf"]
									snake_case      : Union[str, Any]							=   ["werewolf"]
									# S = 0, D = 0, I = 1, N = 9, CER = 1 / 9
									snake_case      : List[str]							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.1111111		) < 1E-6		)

									snake_case      : List[str]							=   ["werewolf"]
									snake_case      : Optional[Any]							=   ["weae     wolf"]
									# S = 1, D = 1, I = 0, N = 8, CER = 0.25
									snake_case      : Optional[int]							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.25		) < 1E-6		)

									# consecutive whitespaces case 1
									snake_case      : Optional[int]							=   ["were wolf"]
									snake_case      : Dict							=   ["were               wolf"]
									# S = 0, D = 0, I = 0, N = 9, CER = 0
									snake_case      : Dict							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.0		) < 1E-6		)

									# consecutive whitespaces case 2
									snake_case      : Dict							=   ["were   wolf"]
									snake_case      : Dict							=   ["were               wolf"]
									# S = 0, D = 0, I = 0, N = 9, CER = 0
									snake_case      : Optional[int]							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.0		) < 1E-6		)



			def 							__lowercase				( self       :							List[Any]		)       ->				Union[str, Any]:
									snake_case      : str							=   ["werewolf"]
									snake_case      : List[Any]							=   ["weaewolf"]
									# S = 1, D = 0, I = 0, N = 8, CER = 0.125
									snake_case      : str							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.125		) < 1E-6		)



			def 							__lowercase				( self       :							int		)       ->				int:
									snake_case      : Dict							=   ["werewolf"]
									snake_case      : Optional[Any]							=   ["wereawolf"]
									# S = 0, D = 1, I = 0, N = 8, CER = 0.125
									snake_case      : List[str]							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.125		) < 1E-6		)



			def 							__lowercase				( self       :							Union[str, Any]		)       ->				List[Any]:
									snake_case      : Tuple							=   ["werewolf"]
									snake_case      : Union[str, Any]							=   ["wereolf"]
									# S = 0, D = 0, I = 1, N = 8, CER = 0.125
									snake_case      : str							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.125		) < 1E-6		)



			def 							__lowercase				( self       :							int		)       ->				List[str]:
									snake_case      : int							=   ["werewolf"]
									snake_case      : Optional[Any]							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertEqual(_lowercase      ,  0.0		)



			def 							__lowercase				( self       :							List[Any]		)       ->				Optional[Any]:
									snake_case      : str							=   ["werewolf", "I am your father"]
									snake_case      : str							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertEqual(_lowercase      ,  0.0		)

									snake_case      : Union[str, Any]							=   ["werewolf", "I am your father", "doge"]
									snake_case      : str							=   ["werxwolf", "I       am your father", "doge"]
									# S = 1, D = 0, I = 0, N = 28, CER = 1 / 28
									snake_case      : Dict							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.03571428		) < 1E-6		)



			def 							__lowercase				( self       :							Any		)       ->				Union[str, Any]:
									snake_case      : Union[str, Any]							=   ["My hovercraft", "is full of eels"]
									snake_case      : List[str]							=   ["My hovercraft is full", " of eels"]
									# S = 0, D = 0, I = 2, N = 28, CER = 2 / 28
									# whitespace at the front of " of eels" will be strip during preporcessing
									# so need to insert 2 whitespaces
									snake_case      : int							=   cer.compute(predictions=_lowercase      ,  references=_lowercase      ,  concatenate_texts=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.071428		) < 1E-6		)



			def 							__lowercase				( self       :							Any		)       ->				Dict:
									snake_case      : Dict							=   ["我能吞下玻璃而不伤身体"]
									snake_case      : List[str]							=   [" 能吞虾玻璃而 不霜身体啦"]
									# S = 3, D = 2, I = 0, N = 11, CER = 5 / 11
									snake_case      : str							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.4545454545		) < 1E-6		)

									snake_case      : List[Any]							=   ["我能吞下玻璃", "而不伤身体"]
									snake_case      : int							=   ["我    能 吞 下 玻 璃", "而不伤身体"]
									# S = 0, D = 5, I = 0, N = 11, CER = 5 / 11
									snake_case      : Dict							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertTrue(abs(char_error_rate - 0.454545454545		) < 1E-6		)

									snake_case      : int							=   ["我能吞下玻璃而不伤身体"]
									snake_case      : int							=   cer.compute(predictions=_lowercase      ,  references=_lowercase		)
									self.assertFalse(_lowercase      ,  0.0		)



			def 							__lowercase				( self       :							List[Any]		)       ->				List[Any]:
									snake_case      : int							=   [""]
									snake_case      : Optional[int]							=   ["Hypothesis"]
									with self.assertRaises(_lowercase		):
															cer.compute(predictions=_lowercase      ,  references=_lowercase		)


if __name__ == "__main__":
			unittest.main()



