import gc
import random
import unittest

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

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

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 				a							(			__lowerCAmelCase       ,			__lowerCAmelCase       ,			unittest.TestCase       ):







 """simple docstring"""






 lowerCamelCase	:Union[str, Any]    			=		StableDiffusionXLImgaImgPipeline
 lowerCamelCase	:Union[str, Any]    			=		TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'''height''', '''width'''}
 lowerCamelCase	:Optional[int]    			=		PipelineTesterMixin.required_optional_params - {'''latents'''}
 lowerCamelCase	:int    			=		TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
 lowerCamelCase	:List[str]    			=		IMAGE_TO_IMAGE_IMAGE_PARAMS
 lowerCamelCase	:Tuple    			=		IMAGE_TO_IMAGE_IMAGE_PARAMS



 def      UpperCAmelCase							(					self							)  ->					str:
        torch.manual_seed(0							)
        _A        =  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""")		,				attention_head_dim=(2, 4)		,				use_linear_projection=lowerCAmelCase_		,				addition_embed_type="""text_time"""		,				addition_time_embed_dim=8		,				transformer_layers_per_block=(1, 2)		,				projection_class_embeddings_input_dim=80		,				cross_attention_dim=64		,				)
        _A        =  EulerDiscreteScheduler(
            beta_start=0.0_0085		,				beta_end=0.012		,				steps_offset=1		,				beta_schedule="""scaled_linear"""		,				timestep_spacing="""leading"""		,				)
        torch.manual_seed(0							)
        _A        =  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		,				sample_size=1_28		,				)
        torch.manual_seed(0							)
        _A        =  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		,				hidden_act="""gelu"""		,				projection_dim=32		,				)
        _A        =  CLIPTextModel(lowerCAmelCase_							)
        _A        =  CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""		,				local_files_only=lowerCAmelCase_							)

        _A        =  CLIPTextModelWithProjection(lowerCAmelCase_							)
        _A        =  CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""		,				local_files_only=lowerCAmelCase_							)

        _A        =  {
            """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      UpperCAmelCase							(					self		,				lowerCAmelCase_		,				lowerCAmelCase_=0							)  ->					List[str]:
        _A        =  floats_tensor((1, 3, 32, 32)		,				rng=random.Random(lowerCAmelCase_							)							).to(lowerCAmelCase_							)
        _A        =  image / 2 + 0.5
        if str(lowerCAmelCase_							).startswith("""mps"""							):
               _A        =  torch.manual_seed(lowerCAmelCase_							)
        else:
               _A        =  torch.Generator(device=lowerCAmelCase_							).manual_seed(lowerCAmelCase_							)
        _A        =  {
            """prompt""": """A painting of a squirrel eating a burger""",
            """image""": image,
            """generator""": generator,
            """num_inference_steps""": 2,
            """guidance_scale""": 5.0,
            """output_type""": """numpy""",
            """strength""": 0.75,
        }
        return inputs



 def      UpperCAmelCase							(					self							)  ->					List[str]:
        _A        =  """cpu"""  # ensure determinism for the device-dependent torch.Generator
        _A        =  self.get_dummy_components()
        _A        =  StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_							)
        _A        =  sd_pipe.to(lowerCAmelCase_							)
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_							)

        _A        =  self.get_dummy_inputs(lowerCAmelCase_							)
        _A        =  sd_pipe(**lowerCAmelCase_							).images
        _A        =  image[0, -3:, -3:, -1]

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

        _A        =  np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165]							)

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



 def      UpperCAmelCase							(					self							)  ->					Union[str, Any]:
        super().test_attention_slicing_forward_pass(expected_max_diff=3E-3							)



 def      UpperCAmelCase							(					self							)  ->					Any:
        super().test_inference_batch_single_identical(expected_max_diff=3E-3							)



 def      UpperCAmelCase							(					self							)  ->					Union[str, Any]:
        pass



 def      UpperCAmelCase							(					self							)  ->					Union[str, Any]:
        _A        =  self.get_dummy_components()
        _A        =  StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_							)
        _A        =  sd_pipe.to(lowerCAmelCase_							)
        _A        =  sd_pipe.to(lowerCAmelCase_							)
        sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_							)

        # forward without prompt embeds
        _A        =  self.get_dummy_inputs(lowerCAmelCase_							)
        _A        =  3 * ["""this is a negative prompt"""]
        _A        =  negative_prompt
        _A        =  3 * [inputs["""prompt"""]]

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

        # forward with prompt embeds
        _A        =  self.get_dummy_inputs(lowerCAmelCase_							)
        _A        =  3 * ["""this is a negative prompt"""]
        _A        =  3 * [inputs.pop("""prompt"""							)]

        (
            (
            _A
        )   ,  (
            _A
        )   ,  (
            _A
        )   ,  (
            _A
        )   ,  
        )        =  sd_pipe.encode_prompt(lowerCAmelCase_		,				negative_prompt=lowerCAmelCase_							)

        _A        =  sd_pipe(
            **lowerCAmelCase_		,				prompt_embeds=lowerCAmelCase_		,				negative_prompt_embeds=lowerCAmelCase_		,				pooled_prompt_embeds=lowerCAmelCase_		,				negative_pooled_prompt_embeds=lowerCAmelCase_		,				)
        _A        =  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



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







 """simple docstring"""






 def      UpperCAmelCase							(					self							)  ->					Union[str, Any]:
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()



 def      UpperCAmelCase							(					self		,				lowerCAmelCase_		,				lowerCAmelCase_="cpu"		,				lowerCAmelCase_=torch.floataa		,				lowerCAmelCase_=0							)  ->					Union[str, Any]:
        _A        =  torch.Generator(device=lowerCAmelCase_							).manual_seed(lowerCAmelCase_							)
        _A        =  np.random.RandomState(lowerCAmelCase_							).standard_normal((1, 4, 64, 64)							)
        _A        =  torch.from_numpy(lowerCAmelCase_							).to(device=lowerCAmelCase_		,				dtype=lowerCAmelCase_							)
        _A        =  {
            """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      UpperCAmelCase							(					self							)  ->					Tuple:
        _A        =  DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base"""							)
        pipe.to(lowerCAmelCase_							)
        pipe.set_progress_bar_config(disable=lowerCAmelCase_							)

        _A        =  self.get_inputs(lowerCAmelCase_							)
        _A        =  pipe(**lowerCAmelCase_							).images
        _A        =  image[0, -3:, -3:, -1].flatten()

        assert image.shape == (1, 5_12, 5_12, 3)
        _A        =  np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506]							)
        assert np.abs(image_slice - expected_slice							).max() < 7E-3





import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bert import BertTokenizer


_SCREAMING_SNAKE_CASE										=						logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE										=						{'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}

_SCREAMING_SNAKE_CASE										=						{
    'vocab_file': {
        'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/vocab.txt',
        'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/vocab.txt',
        'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/vocab.txt',
        'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/vocab.txt',
        'bert-base-multilingual-uncased': (
            'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/vocab.txt'
        ),
        'bert-base-multilingual-cased': 'https://huggingface.co/bert-base-multilingual-cased/resolve/main/vocab.txt',
        'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/vocab.txt',
        'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/vocab.txt',
        'bert-large-uncased-whole-word-masking': (
            'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/vocab.txt'
        ),
        'bert-large-cased-whole-word-masking': (
            'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/vocab.txt'
        ),
        'bert-large-uncased-whole-word-masking-finetuned-squad': (
            'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt'
        ),
        'bert-large-cased-whole-word-masking-finetuned-squad': (
            'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/vocab.txt'
        ),
        'bert-base-cased-finetuned-mrpc': (
            'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/vocab.txt'
        ),
        'bert-base-german-dbmdz-cased': 'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/vocab.txt',
        'bert-base-german-dbmdz-uncased': (
            'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/vocab.txt'
        ),
        'TurkuNLP/bert-base-finnish-cased-v1': (
            'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/vocab.txt'
        ),
        'TurkuNLP/bert-base-finnish-uncased-v1': (
            'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/vocab.txt'
        ),
        'wietsedv/bert-base-dutch-cased': (
            'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/vocab.txt'
        ),
    },
    'tokenizer_file': {
        'bert-base-uncased': 'https://huggingface.co/bert-base-uncased/resolve/main/tokenizer.json',
        'bert-large-uncased': 'https://huggingface.co/bert-large-uncased/resolve/main/tokenizer.json',
        'bert-base-cased': 'https://huggingface.co/bert-base-cased/resolve/main/tokenizer.json',
        'bert-large-cased': 'https://huggingface.co/bert-large-cased/resolve/main/tokenizer.json',
        'bert-base-multilingual-uncased': (
            'https://huggingface.co/bert-base-multilingual-uncased/resolve/main/tokenizer.json'
        ),
        'bert-base-multilingual-cased': (
            'https://huggingface.co/bert-base-multilingual-cased/resolve/main/tokenizer.json'
        ),
        'bert-base-chinese': 'https://huggingface.co/bert-base-chinese/resolve/main/tokenizer.json',
        'bert-base-german-cased': 'https://huggingface.co/bert-base-german-cased/resolve/main/tokenizer.json',
        'bert-large-uncased-whole-word-masking': (
            'https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/tokenizer.json'
        ),
        'bert-large-cased-whole-word-masking': (
            'https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/tokenizer.json'
        ),
        'bert-large-uncased-whole-word-masking-finetuned-squad': (
            'https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json'
        ),
        'bert-large-cased-whole-word-masking-finetuned-squad': (
            'https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/tokenizer.json'
        ),
        'bert-base-cased-finetuned-mrpc': (
            'https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/tokenizer.json'
        ),
        'bert-base-german-dbmdz-cased': (
            'https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/tokenizer.json'
        ),
        'bert-base-german-dbmdz-uncased': (
            'https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/tokenizer.json'
        ),
        'TurkuNLP/bert-base-finnish-cased-v1': (
            'https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/tokenizer.json'
        ),
        'TurkuNLP/bert-base-finnish-uncased-v1': (
            'https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/tokenizer.json'
        ),
        'wietsedv/bert-base-dutch-cased': (
            'https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/tokenizer.json'
        ),
    },
}

_SCREAMING_SNAKE_CASE										=						{
    'bert-base-uncased': 512,
    'bert-large-uncased': 512,
    'bert-base-cased': 512,
    'bert-large-cased': 512,
    'bert-base-multilingual-uncased': 512,
    'bert-base-multilingual-cased': 512,
    'bert-base-chinese': 512,
    'bert-base-german-cased': 512,
    'bert-large-uncased-whole-word-masking': 512,
    'bert-large-cased-whole-word-masking': 512,
    'bert-large-uncased-whole-word-masking-finetuned-squad': 512,
    'bert-large-cased-whole-word-masking-finetuned-squad': 512,
    'bert-base-cased-finetuned-mrpc': 512,
    'bert-base-german-dbmdz-cased': 512,
    'bert-base-german-dbmdz-uncased': 512,
    'TurkuNLP/bert-base-finnish-cased-v1': 512,
    'TurkuNLP/bert-base-finnish-uncased-v1': 512,
    'wietsedv/bert-base-dutch-cased': 512,
}

_SCREAMING_SNAKE_CASE										=						{
    'bert-base-uncased': {'do_lower_case': True},
    'bert-large-uncased': {'do_lower_case': True},
    'bert-base-cased': {'do_lower_case': False},
    'bert-large-cased': {'do_lower_case': False},
    'bert-base-multilingual-uncased': {'do_lower_case': True},
    'bert-base-multilingual-cased': {'do_lower_case': False},
    'bert-base-chinese': {'do_lower_case': False},
    'bert-base-german-cased': {'do_lower_case': False},
    'bert-large-uncased-whole-word-masking': {'do_lower_case': True},
    'bert-large-cased-whole-word-masking': {'do_lower_case': False},
    'bert-large-uncased-whole-word-masking-finetuned-squad': {'do_lower_case': True},
    'bert-large-cased-whole-word-masking-finetuned-squad': {'do_lower_case': False},
    'bert-base-cased-finetuned-mrpc': {'do_lower_case': False},
    'bert-base-german-dbmdz-cased': {'do_lower_case': False},
    'bert-base-german-dbmdz-uncased': {'do_lower_case': True},
    'TurkuNLP/bert-base-finnish-cased-v1': {'do_lower_case': False},
    'TurkuNLP/bert-base-finnish-uncased-v1': {'do_lower_case': True},
    'wietsedv/bert-base-dutch-cased': {'do_lower_case': False},
}



class 				a							(			__lowerCAmelCase       ):







 """simple docstring"""






 lowerCamelCase	:Tuple    			=		VOCAB_FILES_NAMES
 lowerCamelCase	:Union[str, Any]    			=		PRETRAINED_VOCAB_FILES_MAP
 lowerCamelCase	:Dict    			=		PRETRAINED_INIT_CONFIGURATION
 lowerCamelCase	:Optional[Any]    			=		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 lowerCamelCase	:Optional[Any]    			=		BertTokenizer



 def __init__(					self		,				lowerCAmelCase_=None		,				lowerCAmelCase_=None		,				lowerCAmelCase_=True		,				lowerCAmelCase_="[UNK]"		,				lowerCAmelCase_="[SEP]"		,				lowerCAmelCase_="[PAD]"		,				lowerCAmelCase_="[CLS]"		,				lowerCAmelCase_="[MASK]"		,				lowerCAmelCase_=True		,				lowerCAmelCase_=None		,				**lowerCAmelCase_		,				)  ->					List[str]:
        super().__init__(
            lowerCAmelCase_		,				tokenizer_file=lowerCAmelCase_		,				do_lower_case=lowerCAmelCase_		,				unk_token=lowerCAmelCase_		,				sep_token=lowerCAmelCase_		,				pad_token=lowerCAmelCase_		,				cls_token=lowerCAmelCase_		,				mask_token=lowerCAmelCase_		,				tokenize_chinese_chars=lowerCAmelCase_		,				strip_accents=lowerCAmelCase_		,				**lowerCAmelCase_		,				)

        _A        =  json.loads(self.backend_tokenizer.normalizer.__getstate__()							)
        if (
            normalizer_state.get("""lowercase"""		,				lowerCAmelCase_							) != do_lower_case
            or normalizer_state.get("""strip_accents"""		,				lowerCAmelCase_							) != strip_accents
            or normalizer_state.get("""handle_chinese_chars"""		,				lowerCAmelCase_							) != tokenize_chinese_chars
        ):
               _A        =  getattr(lowerCAmelCase_		,				normalizer_state.pop("""type"""							)							)
               _A        =  do_lower_case
               _A        =  strip_accents
               _A        =  tokenize_chinese_chars
               _A        =  normalizer_class(**lowerCAmelCase_							)

        _A        =  do_lower_case



 def      UpperCAmelCase							(					self		,				lowerCAmelCase_		,				lowerCAmelCase_=None							)  ->					List[str]:
        _A        =  [self.cls_token_id] + token_ids_a + [self.sep_token_id]

        if token_ids_a:
               output += token_ids_a + [self.sep_token_id]

        return output



 def      UpperCAmelCase							(					self		,				lowerCAmelCase_		,				lowerCAmelCase_ = None							)  ->					List[int]:
        _A        =  [self.sep_token_id]
        _A        =  [self.cls_token_id]
        if token_ids_a is None:
               return len(cls + token_ids_a + sep							) * [0]
        return len(cls + token_ids_a + sep							) * [0] + len(token_ids_a + sep							) * [1]



 def      UpperCAmelCase							(					self		,				lowerCAmelCase_		,				lowerCAmelCase_ = None							)  ->					Tuple[str]:
        _A        =  self._tokenizer.model.save(lowerCAmelCase_		,				name=lowerCAmelCase_							)
        return tuple(lowerCAmelCase_							)




