





'''simple docstring'''


import gc
import random
import tempfile
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.semantic_stable_diffusion import SemanticStableDiffusionPipeline as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()
class    a_     (       unittest.TestCase							):





     def 							lowercase__   (				self	:      int		):





        """simple docstring"""




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





     @property
     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        lowercase_    :int					    =				1
        lowercase_    :Union[str, Any]					    =				3
        lowercase_    :List[str]					    =				(32, 32)

        lowercase_    :int					    =				floats_tensor((batch_size, num_channels) + sizes			,   rng=random.Random(0		)		).to(snake_case_		)
        return image





     @property
     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        torch.manual_seed(0		)
        lowercase_    :Union[str, Any]					    =				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			,   )
        return model





     @property
     def 							lowercase__   (				self	:      Union[str, Any]		):





        """simple docstring"""




        torch.manual_seed(0		)
        lowercase_    :List[str]					    =				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			,   )
        return model





     @property
     def 							lowercase__   (				self	:      str		):





        """simple docstring"""




        torch.manual_seed(0		)
        lowercase_    :int					    =				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=1_000			,   )
        return CLIPTextModel(snake_case_		)





     @property
     def 							lowercase__   (				self	:      Tuple		):





        """simple docstring"""




        def extract(*lowercase	:      Union[str, Any]			,   **lowercase	:      Any		):
           class    a_     :





                def __init__(				self	:      List[Any]		):





                   """simple docstring"""




                   lowercase_    :Optional[int]					    =				torch.ones([0]		)







                def 							lowercase__   (				self	:      List[str]			,   lowercase	:      Optional[Any]		):





                   """simple docstring"""




                   self.pixel_values.to(snake_case_		)
                   return self







           return Out()

        return extract





     def 							lowercase__   (				self	:      Dict		):





        """simple docstring"""




        lowercase_    :Optional[Any]					    =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
        lowercase_    :Optional[int]					    =				self.dummy_cond_unet
        lowercase_    :int					    =				DDIMScheduler(
            beta_start=0.0_00_85			,   beta_end=0.0_12			,   beta_schedule="scaled_linear"			,   clip_sample=snake_case_			,   set_alpha_to_one=snake_case_			,   )

        lowercase_    :str					    =				self.dummy_vae
        lowercase_    :Union[str, Any]					    =				self.dummy_text_encoder
        lowercase_    :Optional[Any]					    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		)

        # make sure here that pndm scheduler skips prk
        lowercase_    :Any					    =				StableDiffusionPipeline(
            unet=snake_case_			,   scheduler=snake_case_			,   vae=snake_case_			,   text_encoder=snake_case_			,   tokenizer=snake_case_			,   safety_checker=snake_case_			,   feature_extractor=self.dummy_extractor			,   )
        lowercase_    :List[Any]					    =				sd_pipe.to(snake_case_		)
        sd_pipe.set_progress_bar_config(disable=snake_case_		)

        lowercase_    :int					    =				'''A painting of a squirrel eating a burger'''

        lowercase_    :List[Any]					    =				torch.Generator(device=snake_case_		).manual_seed(0		)
        lowercase_    :Tuple					    =				sd_pipe([prompt]			,   generator=snake_case_			,   guidance_scale=6.0			,   num_inference_steps=2			,   output_type="np"		)
        lowercase_    :Any					    =				output.images

        lowercase_    :Any					    =				torch.Generator(device=snake_case_		).manual_seed(0		)
        lowercase_    :Any					    =				sd_pipe(
            [prompt]			,   generator=snake_case_			,   guidance_scale=6.0			,   num_inference_steps=2			,   output_type="np"			,   return_dict=snake_case_			,   )[0]

        lowercase_    :Tuple					    =				image[0, -3:, -3:, -1]
        lowercase_    :Dict					    =				image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        lowercase_    :Union[str, Any]					    =				np.array([0.57_53, 0.61_14, 0.50_01, 0.50_34, 0.54_70, 0.47_29, 0.49_71, 0.48_67, 0.48_67]		)

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





     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        lowercase_    :Any					    =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
        lowercase_    :Union[str, Any]					    =				self.dummy_cond_unet
        lowercase_    :Union[str, Any]					    =				PNDMScheduler(skip_prk_steps=snake_case_		)
        lowercase_    :str					    =				self.dummy_vae
        lowercase_    :Optional[Any]					    =				self.dummy_text_encoder
        lowercase_    :Optional[Any]					    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		)

        # make sure here that pndm scheduler skips prk
        lowercase_    :Any					    =				StableDiffusionPipeline(
            unet=snake_case_			,   scheduler=snake_case_			,   vae=snake_case_			,   text_encoder=snake_case_			,   tokenizer=snake_case_			,   safety_checker=snake_case_			,   feature_extractor=self.dummy_extractor			,   )
        lowercase_    :Tuple					    =				sd_pipe.to(snake_case_		)
        sd_pipe.set_progress_bar_config(disable=snake_case_		)

        lowercase_    :str					    =				'''A painting of a squirrel eating a burger'''
        lowercase_    :Dict					    =				torch.Generator(device=snake_case_		).manual_seed(0		)
        lowercase_    :Optional[Any]					    =				sd_pipe([prompt]			,   generator=snake_case_			,   guidance_scale=6.0			,   num_inference_steps=2			,   output_type="np"		)

        lowercase_    :int					    =				output.images

        lowercase_    :int					    =				torch.Generator(device=snake_case_		).manual_seed(0		)
        lowercase_    :Dict					    =				sd_pipe(
            [prompt]			,   generator=snake_case_			,   guidance_scale=6.0			,   num_inference_steps=2			,   output_type="np"			,   return_dict=snake_case_			,   )[0]

        lowercase_    :Optional[Any]					    =				image[0, -3:, -3:, -1]
        lowercase_    :List[str]					    =				image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        lowercase_    :Optional[Any]					    =				np.array([0.51_22, 0.57_12, 0.48_25, 0.50_53, 0.56_46, 0.47_69, 0.51_79, 0.48_94, 0.49_94]		)

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





     def 							lowercase__   (				self	:      Tuple		):





        """simple docstring"""




        lowercase_    :str					    =				StableDiffusionPipeline.from_pretrained(
            "hf-internal-testing/tiny-stable-diffusion-lms-pipe"			,   safety_checker=snake_case_		)
        assert isinstance(snake_case_			,   snake_case_		)
        assert isinstance(pipe.scheduler			,   snake_case_		)
        assert pipe.safety_checker is None

        lowercase_    :Optional[int]					    =				pipe("example prompt"			,   num_inference_steps=2		).images[0]
        assert image is not None

        # check that there's no error when saving a pipeline with one of the models being None
        with tempfile.TemporaryDirectory() as tmpdirname:
           pipe.save_pretrained(snake_case_		)
           lowercase_    :Optional[int]					    =				StableDiffusionPipeline.from_pretrained(snake_case_		)

        # sanity check that the pipeline still works
        assert pipe.safety_checker is None
        lowercase_    :int					    =				pipe("example prompt"			,   num_inference_steps=2		).images[0]
        assert image is not None







     @unittest.skipIf(torch_device != "cuda"			,   "This test requires a GPU"		)
     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




        lowercase_    :Any					    =				self.dummy_cond_unet
        lowercase_    :Optional[int]					    =				PNDMScheduler(skip_prk_steps=snake_case_		)
        lowercase_    :Any					    =				self.dummy_vae
        lowercase_    :Union[str, Any]					    =				self.dummy_text_encoder
        lowercase_    :Tuple					    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		)

        # put models in fp16
        lowercase_    :str					    =				unet.half()
        lowercase_    :int					    =				vae.half()
        lowercase_    :int					    =				bert.half()

        # make sure here that pndm scheduler skips prk
        lowercase_    :Optional[Any]					    =				StableDiffusionPipeline(
            unet=snake_case_			,   scheduler=snake_case_			,   vae=snake_case_			,   text_encoder=snake_case_			,   tokenizer=snake_case_			,   safety_checker=snake_case_			,   feature_extractor=self.dummy_extractor			,   )
        lowercase_    :Tuple					    =				sd_pipe.to(snake_case_		)
        sd_pipe.set_progress_bar_config(disable=snake_case_		)

        lowercase_    :List[str]					    =				'''A painting of a squirrel eating a burger'''
        lowercase_    :Tuple					    =				sd_pipe([prompt]			,   num_inference_steps=2			,   output_type="np"		).images

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







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





     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




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





     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




        lowercase_    :Any					    =				'''cuda'''
        lowercase_    :str					    =				StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"		)
        lowercase_    :Dict					    =				pipe.to(snake_case_		)
        pipe.set_progress_bar_config(disable=snake_case_		)

        lowercase_    :Optional[Any]					    =				'''a photo of a cat'''
        lowercase_    :Union[str, Any]					    =				{
            '''editing_prompt''': ['''sunglasses'''],
            '''reverse_editing_direction''': [False],
            '''edit_warmup_steps''': 10,
            '''edit_guidance_scale''': 6,
            '''edit_threshold''': 0.95,
            '''edit_momentum_scale''': 0.5,
            '''edit_mom_beta''': 0.6,
        }

        lowercase_    :List[str]					    =				3
        lowercase_    :Any					    =				7

        # no sega enabled
        lowercase_    :List[str]					    =				torch.Generator(snake_case_		)
        generator.manual_seed(snake_case_		)
        lowercase_    :Union[str, Any]					    =				pipe(
            [prompt]			,   generator=snake_case_			,   guidance_scale=snake_case_			,   num_inference_steps=50			,   output_type="np"			,   width=512			,   height=512			,   )

        lowercase_    :Tuple					    =				output.images
        lowercase_    :Union[str, Any]					    =				image[0, -3:, -3:, -1]
        lowercase_    :Any					    =				[
            0.34_67_31_13,
            0.38_49_27_33,
            0.37_59_73_52,
            0.34_08_63_35,
            0.35_65_07_48,
            0.35_57_92_05,
            0.3_38_47_63,
            0.34_34_02_36,
            0.3_57_32_71,
        ]

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

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

        # with sega enabled
        # generator = torch.manual_seed(seed)
        generator.manual_seed(snake_case_		)
        lowercase_    :Tuple					    =				pipe(
            [prompt]			,   generator=snake_case_			,   guidance_scale=snake_case_			,   num_inference_steps=50			,   output_type="np"			,   width=512			,   height=512			,   **snake_case_			,   )

        lowercase_    :Optional[int]					    =				output.images
        lowercase_    :Any					    =				image[0, -3:, -3:, -1]
        lowercase_    :str					    =				[
            0.41_88_78_26,
            0.37_72_87_66,
            0.30_13_82_72,
            0.41_41_63_35,
            0.41_66_49_85,
            0.36_28_33_92,
            0.36_19_12_46,
            0.43_36_44_65,
            0.43_00_17_32,
        ]

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

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





     def 							lowercase__   (				self	:      Union[str, Any]		):





        """simple docstring"""




        lowercase_    :Optional[Any]					    =				'''cuda'''
        lowercase_    :List[Any]					    =				StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"		)
        lowercase_    :Optional[int]					    =				pipe.to(snake_case_		)
        pipe.set_progress_bar_config(disable=snake_case_		)

        lowercase_    :str					    =				'''an image of a crowded boulevard, realistic, 4k'''
        lowercase_    :Tuple					    =				{
            '''editing_prompt''': '''crowd, crowded, people''',
            '''reverse_editing_direction''': True,
            '''edit_warmup_steps''': 10,
            '''edit_guidance_scale''': 8.3,
            '''edit_threshold''': 0.9,
            '''edit_momentum_scale''': 0.5,
            '''edit_mom_beta''': 0.6,
        }

        lowercase_    :Tuple					    =				9
        lowercase_    :Optional[int]					    =				7

        # no sega enabled
        lowercase_    :int					    =				torch.Generator(snake_case_		)
        generator.manual_seed(snake_case_		)
        lowercase_    :List[Any]					    =				pipe(
            [prompt]			,   generator=snake_case_			,   guidance_scale=snake_case_			,   num_inference_steps=50			,   output_type="np"			,   width=512			,   height=512			,   )

        lowercase_    :List[Any]					    =				output.images
        lowercase_    :Optional[Any]					    =				image[0, -3:, -3:, -1]
        lowercase_    :List[str]					    =				[
            0.43_49_79_98,
            0.91_81_40_65,
            0.7_54_07_39,
            0.55_58_02_05,
            0.8_46_72_65,
            0.5_38_96_91,
            0.62_57_45_06,
            0.58_89_77_63,
            0.50_92_67_57,
        ]

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

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

        # with sega enabled
        # generator = torch.manual_seed(seed)
        generator.manual_seed(snake_case_		)
        lowercase_    :Union[str, Any]					    =				pipe(
            [prompt]			,   generator=snake_case_			,   guidance_scale=snake_case_			,   num_inference_steps=50			,   output_type="np"			,   width=512			,   height=512			,   **snake_case_			,   )

        lowercase_    :Tuple					    =				output.images
        lowercase_    :str					    =				image[0, -3:, -3:, -1]
        lowercase_    :List[Any]					    =				[
            0.3_08_97_19,
            0.30_50_01_44,
            0.29_01_60_42,
            0.30_63_09_64,
            0.32_56_87,
            0.29_41_92_25,
            0.2_90_80_91,
            0.28_72_35_98,
            0.27_69_62_94,
        ]

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

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





     def 							lowercase__   (				self	:      List[Any]		):





        """simple docstring"""




        lowercase_    :List[str]					    =				'''cuda'''
        lowercase_    :Any					    =				StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"		)
        lowercase_    :Dict					    =				pipe.to(snake_case_		)
        pipe.set_progress_bar_config(disable=snake_case_		)

        lowercase_    :Any					    =				'''a castle next to a river'''
        lowercase_    :Optional[Any]					    =				{
            '''editing_prompt''': ['''boat on a river, boat''', '''monet, impression, sunrise'''],
            '''reverse_editing_direction''': False,
            '''edit_warmup_steps''': [15, 18],
            '''edit_guidance_scale''': 6,
            '''edit_threshold''': [0.9, 0.8],
            '''edit_momentum_scale''': 0.5,
            '''edit_mom_beta''': 0.6,
        }

        lowercase_    :Optional[Any]					    =				48
        lowercase_    :List[Any]					    =				7

        # no sega enabled
        lowercase_    :int					    =				torch.Generator(snake_case_		)
        generator.manual_seed(snake_case_		)
        lowercase_    :List[Any]					    =				pipe(
            [prompt]			,   generator=snake_case_			,   guidance_scale=snake_case_			,   num_inference_steps=50			,   output_type="np"			,   width=512			,   height=512			,   )

        lowercase_    :int					    =				output.images
        lowercase_    :str					    =				image[0, -3:, -3:, -1]
        lowercase_    :int					    =				[
            0.75_16_35_55,
            0.76_03_71_45,
            0.6_17_85,
            0.9_18_96_73,
            0.8_62_77_01,
            0.85_18_96_94,
            0.8_51_28_13,
            0.87_01_20_76,
            0.8_31_28_57,
        ]

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

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

        # with sega enabled
        # generator = torch.manual_seed(seed)
        generator.manual_seed(snake_case_		)
        lowercase_    :Optional[int]					    =				pipe(
            [prompt]			,   generator=snake_case_			,   guidance_scale=snake_case_			,   num_inference_steps=50			,   output_type="np"			,   width=512			,   height=512			,   **snake_case_			,   )

        lowercase_    :Optional[int]					    =				output.images
        lowercase_    :Any					    =				image[0, -3:, -3:, -1]
        lowercase_    :Dict					    =				[
            0.73_55_33_65,
            0.7_53_72_71,
            0.74_34_19_05,
            0.66_48_03_56,
            0.6_47_29_25,
            0.63_03_94_16,
            0.64_81_29_05,
            0.6_74_97_17,
            0.6_51_71_02,
        ]

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

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







     def 							lowercase__   (				self	:      Tuple		):





        """simple docstring"""




        lowercase_    :Any					    =				'''cuda'''
        lowercase_    :List[str]					    =				StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"			,   torch_dtype=torch.floataa		)
        lowercase_    :List[str]					    =				pipe.to(snake_case_		)
        pipe.set_progress_bar_config(disable=snake_case_		)

        lowercase_    :int					    =				'''a photo of a cat'''
        lowercase_    :List[str]					    =				{
            '''editing_prompt''': ['''sunglasses'''],
            '''reverse_editing_direction''': [False],
            '''edit_warmup_steps''': 10,
            '''edit_guidance_scale''': 6,
            '''edit_threshold''': 0.95,
            '''edit_momentum_scale''': 0.5,
            '''edit_mom_beta''': 0.6,
        }

        lowercase_    :str					    =				3
        lowercase_    :List[str]					    =				7

        # no sega enabled
        lowercase_    :int					    =				torch.Generator(snake_case_		)
        generator.manual_seed(snake_case_		)
        lowercase_    :int					    =				pipe(
            [prompt]			,   generator=snake_case_			,   guidance_scale=snake_case_			,   num_inference_steps=50			,   output_type="np"			,   width=512			,   height=512			,   )

        lowercase_    :Tuple					    =				output.images
        lowercase_    :List[Any]					    =				image[0, -3:, -3:, -1]
        lowercase_    :Optional[int]					    =				[
            0.34_88_76_95,
            0.3_87_69_53,
            0.3_75,
            0.34_42_38_28,
            0.3_58_15_43,
            0.35_71_77_73,
            0.3_38_37_89,
            0.34_57_03_12,
            0.35_93_75,
        ]

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

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

        # with sega enabled
        # generator = torch.manual_seed(seed)
        generator.manual_seed(snake_case_		)
        lowercase_    :Union[str, Any]					    =				pipe(
            [prompt]			,   generator=snake_case_			,   guidance_scale=snake_case_			,   num_inference_steps=50			,   output_type="np"			,   width=512			,   height=512			,   **snake_case_			,   )

        lowercase_    :Optional[int]					    =				output.images
        lowercase_    :str					    =				image[0, -3:, -3:, -1]
        lowercase_    :Optional[Any]					    =				[
            0.42_28_51_56,
            0.36_91_40_62,
            0.29_07_71_48,
            0.42_04_10_16,
            0.41_91_89_45,
            0.35_49_80_47,
            0.3_61_81_64,
            0.4_42_38_28,
            0.43_11_52_34,
        ]

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

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









'''simple docstring'''


import platform
from argparse import ArgumentParser

import huggingface_hub
import pandas
import pyarrow

from datasets import __version__ as version
from datasets.commands import BaseDatasetsCLICommand
def 							UpperCAmelCase_						(		__lowerCamelCase      :      Optional[int]				):
   return EnvironmentCommand()


class    a_     (       _lowerCAmelCase							):





     @staticmethod
     def 							lowercase__   (				lowercase	:      ArgumentParser		):





        """simple docstring"""




        lowercase_    :Optional[int]					    =				parser.add_parser("env"			,   help="Print relevant system environment info."		)
        download_parser.set_defaults(func=lowercase		)





     def 							lowercase__   (				self	:      List[str]		):





        """simple docstring"""




        lowercase_    :Tuple					    =				{
            "`datasets` version": version,
            "Platform": platform.platform(),
            "Python version": platform.python_version(),
            "Huggingface_hub version": huggingface_hub.__version__,
            "PyArrow version": pyarrow.__version__,
            "Pandas version": pandas.__version__,
        }

        print("\nCopy-and-paste the text below in your GitHub issue.\n"		)
        print(self.format_dict(lowercase		)		)

        return info







     @staticmethod
     def 							lowercase__   (				lowercase	:      Dict		):





        """simple docstring"""




        return "\n".join([F'- {prop}: {val}' for prop, val in d.items()]		) + "\n"


