


'''simple docstring'''

import json
import os
import random
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 IMAGE_PROCESSOR_NAME, is_vision_available


if is_vision_available():
       from PIL import Image

       from transformers import FlavaImageProcessor, FlavaProcessor
       from transformers.models.flava.image_processing_flava import (
           FLAVA_CODEBOOK_MEAN,
           FLAVA_CODEBOOK_STD,
           FLAVA_IMAGE_MEAN,
           FLAVA_IMAGE_STD,
       )







@require_vision
class 			UpperCAmelCase			(							unittest.TestCase):

 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    UpperCamelCase__			    =    tempfile.mkdtemp()

    # fmt: off
    UpperCamelCase__			    =    ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest"]
    # fmt: on
    UpperCamelCase__			    =    os.path.join(self.tmpdirname,       VOCAB_FILES_NAMES["vocab_file"]       )

    with open(self.vocab_file,       "w",       encoding="utf-8"       ) as fp:
       fp.write("".join([x + "\n" for x in vocab_tokens]       )       )

    UpperCamelCase__			    =    {
        "image_mean": FLAVA_IMAGE_MEAN,
        "image_std": FLAVA_IMAGE_STD,
        "do_normalize": True,
        "do_resize": True,
        "size": 224,
        "do_center_crop": True,
        "crop_size": 224,
        "input_size_patches": 14,
        "total_mask_patches": 75,
        "mask_group_max_patches": None,
        "mask_group_min_patches": 16,
        "mask_group_min_aspect_ratio": 0.3,
        "mask_group_max_aspect_ratio": None,
        "codebook_do_resize": True,
        "codebook_size": 112,
        "codebook_do_center_crop": True,
        "codebook_crop_size": 112,
        "codebook_do_map_pixels": True,
        "codebook_do_normalize": True,
        "codebook_image_mean": FLAVA_CODEBOOK_MEAN,
        "codebook_image_std": FLAVA_CODEBOOK_STD,
    }

    UpperCamelCase__			    =    os.path.join(self.tmpdirname,       a_       )
    with open(self.image_processor_file,       "w",       encoding="utf-8"       ) as fp:
       json.dump(a_,       a_       )

 def 		lowercase_    (			self			:						List[str],       **a_			:						int       ):





    """simple docstring"""



    return BertTokenizer.from_pretrained(self.tmpdirname,       **a_       )

 def 		lowercase_    (			self			:						str,       **a_			:						Any       ):





    """simple docstring"""



    return BertTokenizerFast.from_pretrained(self.tmpdirname,       **a_       )

 def 		lowercase_    (			self			:						Dict,       **a_			:						Tuple       ):





    """simple docstring"""



    return FlavaImageProcessor.from_pretrained(self.tmpdirname,       **a_       )

 def 		lowercase_    (			self			:						List[str]       ):





    """simple docstring"""



    shutil.rmtree(self.tmpdirname       )

 def 		lowercase_    (			self			:						Tuple       ):





    """simple docstring"""



    UpperCamelCase__			    =    [np.random.randint(255,       size=(3, 30, 400),       dtype=np.uinta       )]

    UpperCamelCase__			    =    [Image.fromarray(np.moveaxis(a_,       0,       -1       )       ) for x in image_inputs]

    return image_inputs

 def 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.get_tokenizer()
    UpperCamelCase__			    =    self.get_rust_tokenizer()
    UpperCamelCase__			    =    self.get_image_processor()

    UpperCamelCase__			    =    FlavaProcessor(tokenizer=a_,       image_processor=a_       )
    processor_slow.save_pretrained(self.tmpdirname       )
    UpperCamelCase__			    =    FlavaProcessor.from_pretrained(self.tmpdirname,       use_fast=a_       )

    UpperCamelCase__			    =    FlavaProcessor(tokenizer=a_,       image_processor=a_       )
    processor_fast.save_pretrained(self.tmpdirname       )
    UpperCamelCase__			    =    FlavaProcessor.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,       a_       )
    self.assertIsInstance(processor_fast.tokenizer,       a_       )

    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,       a_       )
    self.assertIsInstance(processor_fast.image_processor,       a_       )

 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    UpperCamelCase__			    =    FlavaProcessor(tokenizer=self.get_tokenizer(),       image_processor=self.get_image_processor()       )
    processor.save_pretrained(self.tmpdirname       )

    UpperCamelCase__			    =    self.get_tokenizer(bos_token="(BOS)",       eos_token="(EOS)"       )
    UpperCamelCase__			    =    self.get_image_processor(do_normalize=a_,       padding_value=1.0       )

    UpperCamelCase__			    =    FlavaProcessor.from_pretrained(
        self.tmpdirname,       bos_token="(BOS)",       eos_token="(EOS)",       do_normalize=a_,       padding_value=1.0       )

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

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

 def 		lowercase_    (			self			:						int       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.get_image_processor()
    UpperCamelCase__			    =    self.get_tokenizer()

    UpperCamelCase__			    =    FlavaProcessor(tokenizer=a_,       image_processor=a_       )

    UpperCamelCase__			    =    self.prepare_image_inputs()

    UpperCamelCase__			    =    image_processor(a_,       return_tensors="np"       )
    UpperCamelCase__			    =    processor(images=a_,       return_tensors="np"       )

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

    # With rest of the args
    random.seed(1234       )
    UpperCamelCase__			    =    image_processor(
        a_,       return_image_mask=a_,       return_codebook_pixels=a_,       return_tensors="np"       )
    random.seed(1234       )
    UpperCamelCase__			    =    processor(
        images=a_,       return_image_mask=a_,       return_codebook_pixels=a_,       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 		lowercase_    (			self			:						Any       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.get_image_processor()
    UpperCamelCase__			    =    self.get_tokenizer()

    UpperCamelCase__			    =    FlavaProcessor(tokenizer=a_,       image_processor=a_       )

    UpperCamelCase__			    =    "lower newer"

    UpperCamelCase__			    =    processor(text=a_       )

    UpperCamelCase__			    =    tokenizer(a_       )

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

 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.get_image_processor()
    UpperCamelCase__			    =    self.get_tokenizer()

    UpperCamelCase__			    =    FlavaProcessor(tokenizer=a_,       image_processor=a_       )

    UpperCamelCase__			    =    "lower newer"
    UpperCamelCase__			    =    self.prepare_image_inputs()

    UpperCamelCase__			    =    processor(text=a_,       images=a_       )

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

    # add extra args
    UpperCamelCase__			    =    processor(text=a_,       images=a_,       return_codebook_pixels=a_,       return_image_mask=a_       )

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

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

 def 		lowercase_    (			self			:						Tuple       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.get_image_processor()
    UpperCamelCase__			    =    self.get_tokenizer()

    UpperCamelCase__			    =    FlavaProcessor(tokenizer=a_,       image_processor=a_       )

    UpperCamelCase__			    =    [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]

    UpperCamelCase__			    =    processor.batch_decode(a_       )
    UpperCamelCase__			    =    tokenizer.batch_decode(a_       )

    self.assertListEqual(a_,       a_       )

 def 		lowercase_    (			self			:						Optional[int]       ):





    """simple docstring"""



    UpperCamelCase__			    =    self.get_image_processor()
    UpperCamelCase__			    =    self.get_tokenizer()

    UpperCamelCase__			    =    FlavaProcessor(tokenizer=a_,       image_processor=a_       )

    UpperCamelCase__			    =    "lower newer"
    UpperCamelCase__			    =    self.prepare_image_inputs()

    UpperCamelCase__			    =    processor(text=a_,       images=a_       )

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



import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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


enable_full_determinism()







class 					snake_case__(				UpperCAmelCase__,    UpperCAmelCase__,    unittest.TestCase				):







						'''simple docstring'''




						SCREAMING_SNAKE_CASE__   :	str       =				StableDiffusionXLPipeline
						SCREAMING_SNAKE_CASE__   :	Dict       =				TEXT_TO_IMAGE_PARAMS
						SCREAMING_SNAKE_CASE__   :	Optional[int]       =				TEXT_TO_IMAGE_BATCH_PARAMS
						SCREAMING_SNAKE_CASE__   :	Optional[Any]       =				TEXT_TO_IMAGE_IMAGE_PARAMS
						SCREAMING_SNAKE_CASE__   :	int       =				TEXT_TO_IMAGE_IMAGE_PARAMS




						def     lowercase_			(					self				)       ->     int:
										torch.manual_seed(0				)
										lowerCAmelCase_			:   Tuple     					=					UNetaDConditionModel(
										    block_out_channels=(3_2, 6_4) ,    layers_per_block=2 ,    sample_size=3_2 ,    in_channels=4 ,    out_channels=4 ,    down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') ,    up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') ,    attention_head_dim=(2, 4) ,    use_linear_projection=__lowercase ,    addition_embed_type='''text_time''' ,    addition_time_embed_dim=8 ,    transformer_layers_per_block=(1, 2) ,    projection_class_embeddings_input_dim=8_0 ,    cross_attention_dim=6_4 ,    )
										lowerCAmelCase_			:   Any     					=					EulerDiscreteScheduler(
										    beta_start=0.0_00_85 ,    beta_end=0.0_12 ,    steps_offset=1 ,    beta_schedule='''scaled_linear''' ,    timestep_spacing='''leading''' ,    )
										torch.manual_seed(0				)
										lowerCAmelCase_			:   Any     					=					AutoencoderKL(
										    block_out_channels=[3_2, 6_4] ,    in_channels=3 ,    out_channels=3 ,    down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] ,    up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] ,    latent_channels=4 ,    sample_size=1_2_8 ,    )
										torch.manual_seed(0				)
										lowerCAmelCase_			:   Dict     					=					CLIPTextConfig(
										    bos_token_id=0 ,    eos_token_id=2 ,    hidden_size=3_2 ,    intermediate_size=3_7 ,    layer_norm_eps=1e-05 ,    num_attention_heads=4 ,    num_hidden_layers=5 ,    pad_token_id=1 ,    vocab_size=1_0_0_0 ,    hidden_act='''gelu''' ,    projection_dim=3_2 ,    )
										lowerCAmelCase_			:   str     					=					CLIPTextModel(__lowercase				)
										lowerCAmelCase_			:   List[str]     					=					CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,    local_files_only=__lowercase				)

										lowerCAmelCase_			:   Tuple     					=					CLIPTextModelWithProjection(__lowercase				)
										lowerCAmelCase_			:   Optional[Any]     					=					CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' ,    local_files_only=__lowercase				)

										lowerCAmelCase_			:   int     					=					{
										    '''unet''': unet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''text_encoder_2''': text_encoder_a,
										    '''tokenizer_2''': tokenizer_a,
										    # "safety_checker": None,
										    # "feature_extractor": None,
										}
										return components




						def     lowercase_			(					self ,    __lowercase ,    __lowercase=0				)       ->     Dict:
										if str(__lowercase				).startswith('''mps'''				):
														lowerCAmelCase_			:   Dict     					=					torch.manual_seed(__lowercase				)
										else:
														lowerCAmelCase_			:   Dict     					=					torch.Generator(device=__lowercase				).manual_seed(__lowercase				)
										lowerCAmelCase_			:   Dict     					=					{
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''guidance_scale''': 5.0,
										    '''output_type''': '''numpy''',
										}
										return inputs




						def     lowercase_			(					self				)       ->     Optional[Any]:
										lowerCAmelCase_			:   Union[str, Any]     					=					'''cpu'''  # ensure determinism for the device-dependent torch.Generator
										lowerCAmelCase_			:   Any     					=					self.get_dummy_components()
										lowerCAmelCase_			:   Optional[int]     					=					StableDiffusionXLPipeline(**__lowercase				)
										lowerCAmelCase_			:   Optional[int]     					=					sd_pipe.to(__lowercase				)
										sd_pipe.set_progress_bar_config(disable=__lowercase				)

										lowerCAmelCase_			:   Dict     					=					self.get_dummy_inputs(__lowercase				)
										lowerCAmelCase_			:   str     					=					sd_pipe(**__lowercase				).images
										lowerCAmelCase_			:   Any     					=					image[0, -3:, -3:, -1]

										assert image.shape == (1, 6_4, 6_4, 3)
										lowerCAmelCase_			:   str     					=					np.array([0.58_73, 0.61_28, 0.47_97, 0.51_22, 0.56_74, 0.46_39, 0.52_27, 0.51_49, 0.47_47]				)

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




						def     lowercase_			(					self				)       ->     List[Any]:
										lowerCAmelCase_			:   Any     					=					self.get_dummy_components()
										lowerCAmelCase_			:   List[Any]     					=					StableDiffusionXLPipeline(**__lowercase				)
										lowerCAmelCase_			:   List[Any]     					=					sd_pipe.to(__lowercase				)
										lowerCAmelCase_			:   int     					=					sd_pipe.to(__lowercase				)
										sd_pipe.set_progress_bar_config(disable=__lowercase				)

										# forward without prompt embeds
										lowerCAmelCase_			:   Optional[Any]     					=					self.get_dummy_inputs(__lowercase				)
										lowerCAmelCase_			:   List[str]     					=					3 * ['''this is a negative prompt''']
										lowerCAmelCase_			:   Union[str, Any]     					=					negative_prompt
										lowerCAmelCase_			:   Union[str, Any]     					=					3 * [inputs['''prompt''']]

										lowerCAmelCase_			:   str     					=					sd_pipe(**__lowercase				)
										lowerCAmelCase_			:   Any     					=					output.images[0, -3:, -3:, -1]

										# forward with prompt embeds
										lowerCAmelCase_			:   Tuple     					=					self.get_dummy_inputs(__lowercase				)
										lowerCAmelCase_			:   Dict     					=					3 * ['''this is a negative prompt''']
										lowerCAmelCase_			:   Dict     					=					3 * [inputs.pop('''prompt'''				)]

										(
										    (
										    lowerCAmelCase_
										)					,	(
										    lowerCAmelCase_
										)					,	(
										    lowerCAmelCase_
										)					,	(
										    lowerCAmelCase_
										)					,	
										)			:   str     					=					sd_pipe.encode_prompt(__lowercase ,    negative_prompt=__lowercase				)

										lowerCAmelCase_			:   List[Any]     					=					sd_pipe(
										    **__lowercase ,    prompt_embeds=__lowercase ,    negative_prompt_embeds=__lowercase ,    pooled_prompt_embeds=__lowercase ,    negative_pooled_prompt_embeds=__lowercase ,    )
										lowerCAmelCase_			:   int     					=					output.images[0, -3:, -3:, -1]

										# make sure that it's equal
										assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()				).max() < 1e-4




						def     lowercase_			(					self				)       ->     List[str]:
										super().test_attention_slicing_forward_pass(expected_max_diff=3e-3				)




						def     lowercase_			(					self				)       ->     Tuple:
										super().test_inference_batch_single_identical(expected_max_diff=3e-3				)







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







						'''simple docstring'''




						def     lowercase_			(					self				)       ->     int:
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()




						def     lowercase_			(					self ,    __lowercase ,    __lowercase="cpu" ,    __lowercase=torch.floataa ,    __lowercase=0				)       ->     Dict:
										lowerCAmelCase_			:   Any     					=					torch.Generator(device=__lowercase				).manual_seed(__lowercase				)
										lowerCAmelCase_			:   str     					=					np.random.RandomState(__lowercase				).standard_normal((1, 4, 6_4, 6_4)				)
										lowerCAmelCase_			:   List[str]     					=					torch.from_numpy(__lowercase				).to(device=__lowercase ,    dtype=__lowercase				)
										lowerCAmelCase_			:   Optional[Any]     					=					{
										    '''prompt''': '''a photograph of an astronaut riding a horse''',
										    '''latents''': latents,
										    '''generator''': generator,
										    '''num_inference_steps''': 3,
										    '''guidance_scale''': 7.5,
										    '''output_type''': '''numpy''',
										}
										return inputs




						def     lowercase_			(					self				)       ->     List[str]:
										lowerCAmelCase_			:   Optional[int]     					=					DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''				)
										pipe.to(__lowercase				)
										pipe.set_progress_bar_config(disable=__lowercase				)

										lowerCAmelCase_			:   Any     					=					self.get_inputs(__lowercase				)
										lowerCAmelCase_			:   List[str]     					=					pipe(**__lowercase				).images
										lowerCAmelCase_			:   Dict     					=					image[0, -3:, -3:, -1].flatten()

										assert image.shape == (1, 5_1_2, 5_1_2, 3)
										lowerCAmelCase_			:   Optional[int]     					=					np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]				)
										assert np.abs(image_slice - expected_slice				).max() < 7e-3