





'''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 	UpperCamelCase__				(   a__							,   unittest.TestCase     ):



     '''simple docstring'''

     __snake_case					:			Union[str, Any]				=    LDMTextToImagePipeline
     __snake_case					:			int				=    TEXT_TO_IMAGE_PARAMS - {
         "negative_prompt",
         "negative_prompt_embeds",
         "cross_attention_kwargs",
         "prompt_embeds",
     }
     __snake_case					:			List[str]				=    PipelineTesterMixin.required_optional_params - {
         "num_images_per_prompt",
         "callback",
         "callback_steps",
     }
     __snake_case					:			int				=    TEXT_TO_IMAGE_BATCH_PARAMS
     __snake_case					:			str				=    False






     def        SCREAMING_SNAKE_CASE__						(							self		:					int )  ->	str:




           '''simple docstring'''


           torch.manual_seed(0 )
           SCREAMING_SNAKE_CASE	=		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		,)
           SCREAMING_SNAKE_CASE	=		DDIMScheduler(
               beta_start=0.00085		,beta_end=0.012		,beta_schedule="""scaled_linear"""		,clip_sample=_A		,set_alpha_to_one=_A		,)
           torch.manual_seed(0 )
           SCREAMING_SNAKE_CASE	=		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 )
           SCREAMING_SNAKE_CASE	=		CLIPTextConfig(
               bos_token_id=0		,eos_token_id=2		,hidden_size=32		,intermediate_size=37		,layer_norm_eps=1e-0_5		,num_attention_heads=4		,num_hidden_layers=5		,pad_token_id=1		,vocab_size=1000		,)
           SCREAMING_SNAKE_CASE	=		CLIPTextModel(_A )
           SCREAMING_SNAKE_CASE	=		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )

           SCREAMING_SNAKE_CASE	=		{
               'unet': unet,
               'scheduler': scheduler,
               'vqvae': vae,
               'bert': text_encoder,
               'tokenizer': tokenizer,
           }
           return components






     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str]		,lowerCamelCase__		:					List[Any]		,lowerCamelCase__		:					Dict=0 )  ->	int:




           '''simple docstring'''


           if str(_A ).startswith("""mps""" ):
                 SCREAMING_SNAKE_CASE	=		torch.manual_seed(_A )
           else:
                 SCREAMING_SNAKE_CASE	=		torch.Generator(device=_A ).manual_seed(_A )
           SCREAMING_SNAKE_CASE	=		{
               '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        SCREAMING_SNAKE_CASE__						(							self		:					Optional[Any] )  ->	List[str]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		'cpu'  # ensure determinism for the device-dependent torch.Generator

           SCREAMING_SNAKE_CASE	=		self.get_dummy_components()
           SCREAMING_SNAKE_CASE	=		LDMTextToImagePipeline(**_A )
           pipe.to(_A )
           pipe.set_progress_bar_config(disable=_A )

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

           assert image.shape == (1, 16, 16, 3)
           SCREAMING_SNAKE_CASE	=		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 	UpperCamelCase__				(   unittest.TestCase     ):



     '''simple docstring'''

     def        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	int:




           '''simple docstring'''


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






     def        SCREAMING_SNAKE_CASE__						(							self		:					Tuple		,lowerCamelCase__		:					int		,lowerCamelCase__		:					Dict=torch.floataa		,lowerCamelCase__		:					Dict=0 )  ->	Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		torch.manual_seed(_A )
           SCREAMING_SNAKE_CASE	=		np.random.RandomState(_A ).standard_normal((1, 4, 32, 32) )
           SCREAMING_SNAKE_CASE	=		torch.from_numpy(_A ).to(device=_A		,dtype=_A )
           SCREAMING_SNAKE_CASE	=		{
               '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        SCREAMING_SNAKE_CASE__						(							self		:					Any )  ->	Optional[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(_A )
           pipe.set_progress_bar_config(disable=_A )

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

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

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



     '''simple docstring'''

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




           '''simple docstring'''


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






     def        SCREAMING_SNAKE_CASE__						(							self		:					str		,lowerCamelCase__		:					Dict		,lowerCamelCase__		:					Dict=torch.floataa		,lowerCamelCase__		:					Any=0 )  ->	Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		torch.manual_seed(_A )
           SCREAMING_SNAKE_CASE	=		np.random.RandomState(_A ).standard_normal((1, 4, 32, 32) )
           SCREAMING_SNAKE_CASE	=		torch.from_numpy(_A ).to(device=_A		,dtype=_A )
           SCREAMING_SNAKE_CASE	=		{
               '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        SCREAMING_SNAKE_CASE__						(							self		:					List[str] )  ->	Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE	=		LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256""" ).to(_A )
           pipe.set_progress_bar_config(disable=_A )

           SCREAMING_SNAKE_CASE	=		self.get_inputs(_A )
           SCREAMING_SNAKE_CASE	=		pipe(**_A ).images[0]

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









import os
from datetime import datetime as dt

from github import Github


SCREAMING_SNAKE_CASE_		     = [
    """good first issue""",
    """feature request""",
    """wip""",
]



def      __lowercase     (   )				->     Optional[int]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE	=		Github(os.environ["""GITHUB_TOKEN"""]			)
      SCREAMING_SNAKE_CASE	=		g.get_repo("""huggingface/accelerate"""			)
      SCREAMING_SNAKE_CASE	=		repo.get_issues(state="""open"""			)

      for issue in open_issues:
            SCREAMING_SNAKE_CASE	=		sorted([comment for comment in issue.get_comments()]				,		key=lambda _SCREAMING_SNAKE_CASE			: i.created_at				,		reverse=_SCREAMING_SNAKE_CASE			)
            SCREAMING_SNAKE_CASE	=		comments[0] if len(_SCREAMING_SNAKE_CASE			) > 0 else None
            SCREAMING_SNAKE_CASE	=		dt.utcnow()
            SCREAMING_SNAKE_CASE	=		(current_time - issue.updated_at).days
            SCREAMING_SNAKE_CASE	=		(current_time - issue.created_at).days
            if (
                last_comment is not None
                and last_comment.user.login == "github-actions[bot]"
                and days_since_updated > 7
                and days_since_creation >= 30
                and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()			)
            ):
                  # Close issue since it has been 7 days of inactivity since bot mention.
                  issue.edit(state="""closed"""			)
            elif (
                days_since_updated > 23
                and days_since_creation >= 30
                and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()			)
            ):
                  # Add stale comment
                  issue.create_comment(
                      """This issue has been automatically marked as stale because it has not had """
                      """recent activity. If you think this still needs to be addressed """
                      """please comment on this thread.\n\nPlease note that issues that do not follow the """
                      """[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) """
                      """are likely to be ignored."""			)


if __name__ == "__main__":
      main()


