


"""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       (   UpperCamelCase__					,							unittest.TestCase			):
   __UpperCAmelCase				: Tuple													=						LDMTextToImagePipeline
   __UpperCAmelCase				: Optional[Any]													=						TEXT_TO_IMAGE_PARAMS - {
       """negative_prompt""",
       """negative_prompt_embeds""",
       """cross_attention_kwargs""",
       """prompt_embeds""",
   }
   __UpperCAmelCase				: Optional[Any]													=						PipelineTesterMixin.required_optional_params - {
       """num_images_per_prompt""",
       """callback""",
       """callback_steps""",
   }
   __UpperCAmelCase				: str													=						TEXT_TO_IMAGE_BATCH_PARAMS
   __UpperCAmelCase				: List[Any]													=						False







   def 				lowerCamelCase	(			self		)			->	Optional[int]:

       '''simple docstring'''




       torch.manual_seed(0		)
       snake_case					:   Tuple         =					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		,			)
       snake_case					:   List[Any]         =					DDIMScheduler(
           beta_start=0.00085		,			beta_end=0.012		,			beta_schedule="scaled_linear"		,			clip_sample=UpperCamelCase__		,			set_alpha_to_one=UpperCamelCase__		,			)
       torch.manual_seed(0		)
       snake_case					:   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		)
       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=1000		,			)
       snake_case					:   Any         =					CLIPTextModel(UpperCamelCase__		)
       snake_case					:   List[Any]         =					CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		)

       snake_case					:   List[str]         =					{
           "unet": unet,
           "scheduler": scheduler,
           "vqvae": vae,
           "bert": text_encoder,
           "tokenizer": tokenizer,
       }
       return components







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__=0		)			->	Dict:

       '''simple docstring'''




       if str(UpperCamelCase__		).startswith("mps"		):
           snake_case					:   int         =					torch.manual_seed(UpperCamelCase__		)
       else:
           snake_case					:   List[str]         =					torch.Generator(device=UpperCamelCase__		).manual_seed(UpperCamelCase__		)
       snake_case					:   str         =					{
           "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 				lowerCamelCase	(			self		)			->	Dict:

       '''simple docstring'''




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

       snake_case					:   Tuple         =					self.get_dummy_components()
       snake_case					:   Optional[Any]         =					LDMTextToImagePipeline(**UpperCamelCase__		)
       pipe.to(UpperCamelCase__		)
       pipe.set_progress_bar_config(disable=UpperCamelCase__		)

       snake_case					:   Optional[int]         =					self.get_dummy_inputs(UpperCamelCase__		)
       snake_case					:   Any         =					pipe(**UpperCamelCase__		).images
       snake_case					:   Any         =					image[0, -3:, -3:, -1]

       assert image.shape == (1, 16, 16, 3)
       snake_case					:   Optional[int]         =					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			):







   def 				lowerCamelCase	(			self		)			->	Dict:

       '''simple docstring'''




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







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

       '''simple docstring'''




       snake_case					:   Optional[int]         =					torch.manual_seed(UpperCamelCase__		)
       snake_case					:   Any         =					np.random.RandomState(UpperCamelCase__		).standard_normal((1, 4, 32, 32)		)
       snake_case					:   str         =					torch.from_numpy(UpperCamelCase__		).to(device=UpperCamelCase__		,			dtype=UpperCamelCase__		)
       snake_case					:   Optional[int]         =					{
           "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 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




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

       snake_case					:   Optional[int]         =					self.get_inputs(UpperCamelCase__		)
       snake_case					:   Dict         =					pipe(**UpperCamelCase__		).images
       snake_case					:   List[str]         =					image[0, -3:, -3:, -1].flatten()

       assert image.shape == (1, 256, 256, 3)
       snake_case					:   Dict         =					np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878]		)
       snake_case					:   Optional[int]         =					np.abs(expected_slice - image_slice		).max()
       assert max_diff < 1e-3







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







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

       '''simple docstring'''




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







   def 				lowerCamelCase	(			self		,			UpperCamelCase__		,			UpperCamelCase__=torch.floataa		,			UpperCamelCase__=0		)			->	Tuple:

       '''simple docstring'''




       snake_case					:   int         =					torch.manual_seed(UpperCamelCase__		)
       snake_case					:   Dict         =					np.random.RandomState(UpperCamelCase__		).standard_normal((1, 4, 32, 32)		)
       snake_case					:   List[str]         =					torch.from_numpy(UpperCamelCase__		).to(device=UpperCamelCase__		,			dtype=UpperCamelCase__		)
       snake_case					:   Union[str, 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 				lowerCamelCase	(			self		)			->	Optional[Any]:

       '''simple docstring'''




       snake_case					:   int         =					LDMTextToImagePipeline.from_pretrained("CompVis/ldm-text2im-large-256"		).to(UpperCamelCase__		)
       pipe.set_progress_bar_config(disable=UpperCamelCase__		)

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

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









"""simple docstring"""



import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
__snake_case         =					"""src/diffusers"""

# Matches is_xxx_available()
__snake_case         =					re.compile(R"""is\_([a-z_]*)_available\(\)""")
# Matches from xxx import bla
__snake_case         =					re.compile(R"""\s+from\s+\S*\s+import\s+([^\(\s].*)\n""")


__snake_case         =					"""
{0} = None
"""

__snake_case         =					"""
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})

    @classmethod
    def from_config(cls, *args, **kwargs):
        requires_backends(cls, {1})

    @classmethod
    def from_pretrained(cls, *args, **kwargs):
        requires_backends(cls, {1})
"""


__snake_case         =					"""
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
"""







def 						__lowerCAmelCase		(		lowercase						:						Tuple				)			->		str:


    """simple docstring"""





    snake_case					:   Optional[Any]         =					_re_backend.findall(lowercase				)
    if len(lowercase				) == 0:
        return None

    return "_and_".join(lowercase				)







def 						__lowerCAmelCase		(		)			->		Tuple:


    """simple docstring"""





    with open(os.path.join(lowercase		,							"__init__.py"				)		,							"r"		,							encoding="utf-8"		,							newline="\n"				) as f:
        snake_case					:   Tuple         =					f.readlines()

    # Get to the point we do the actual imports for type checking
    snake_case					:   Tuple         =					0
    snake_case					:   Optional[Any]         =					{}
    # Go through the end of the file
    while line_index < len(lowercase				):
        # If the line contains is_backend_available, we grab all objects associated with the `else` block
        snake_case					:   List[Any]         =					find_backend(lines[line_index]				)
        if backend is not None:
            while not lines[line_index].startswith("else:"				):
                line_index += 1
            line_index += 1
            snake_case					:   str         =					[]
            # Until we unindent, add backend objects to the list
            while line_index < len(lowercase				) and len(lines[line_index]				) > 1:
                snake_case					:   List[str]         =					lines[line_index]
                snake_case					:   Any         =					_re_single_line_import.search(lowercase				)
                if single_line_import_search is not None:
                    objects.extend(single_line_import_search.groups()[0].split(", "				)				)
                elif line.startswith(" " * 8				):
                    objects.append(line[8:-2]				)
                line_index += 1

            if len(lowercase				) > 0:
                snake_case					:   Any         =					objects
        else:
            line_index += 1

    return backend_specific_objects







def 						__lowerCAmelCase		(		lowercase						:						Union[str, Any]		,							lowercase						:						Tuple				)			->		int:


    """simple docstring"""





    if name.isupper():
        return DUMMY_CONSTANT.format(lowercase				)
    elif name.islower():
        return DUMMY_FUNCTION.format(lowercase		,							lowercase				)
    else:
        return DUMMY_CLASS.format(lowercase		,							lowercase				)







def 						__lowerCAmelCase		(		lowercase						:						Union[str, Any]=None				)			->		Optional[int]:


    """simple docstring"""





    if backend_specific_objects is None:
        snake_case					:   List[str]         =					read_init()
    # For special correspondence backend to module name as used in the function requires_modulename
    snake_case					:   Dict         =					{}

    for backend, objects in backend_specific_objects.items():
        snake_case					:   Union[str, Any]         =					"[" + ", ".join(F'"{b}"' for b in backend.split("_and_"				)				) + "]"
        snake_case					:   Union[str, Any]         =					"# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
        dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
        dummy_file += "\n".join([create_dummy_object(lowercase		,							lowercase				) for o in objects]				)
        snake_case					:   Optional[Any]         =					dummy_file

    return dummy_files







def 						__lowerCAmelCase		(		lowercase						:						Optional[Any]=False				)			->		Any:


    """simple docstring"""





    snake_case					:   str         =					create_dummy_files()
    # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
    snake_case					:   Dict         =					{"torch": "pt"}

    # Locate actual dummy modules and read their content.
    snake_case					:   Optional[Any]         =					os.path.join(lowercase		,							"utils"				)
    snake_case					:   Union[str, Any]         =					{
        backend: os.path.join(lowercase		,							F'dummy_{short_names.get(lowercase		,							lowercase				)}_objects.py'				)
        for backend in dummy_files.keys()
    }

    snake_case					:   Optional[Any]         =					{}
    for backend, file_path in dummy_file_paths.items():
        if os.path.isfile(lowercase				):
            with open(lowercase		,							"r"		,							encoding="utf-8"		,							newline="\n"				) as f:
                snake_case					:   int         =					f.read()
        else:
            snake_case					:   Optional[Any]         =					""

    for backend in dummy_files.keys():
        if dummy_files[backend] != actual_dummies[backend]:
            if overwrite:
                print(
                    F'Updating diffusers.utils.dummy_{short_names.get(lowercase		,							lowercase				)}_objects.py as the main '
                    "__init__ has new objects."				)
                with open(dummy_file_paths[backend]		,							"w"		,							encoding="utf-8"		,							newline="\n"				) as f:
                    f.write(dummy_files[backend]				)
            else:
                raise ValueError(
                    "The main __init__ has objects that are not present in "
                    F'diffusers.utils.dummy_{short_names.get(lowercase		,							lowercase				)}_objects.py. Run `make fix-copies` '
                    "to fix this."				)


if __name__ == "__main__":
  __snake_case         =					argparse.ArgumentParser()
  parser.add_argument("""--fix_and_overwrite""", action="""store_true""", help="""Whether to fix inconsistencies.""")
  __snake_case         =					parser.parse_args()

  check_dummies(args.fix_and_overwrite)





