



"""simple docstring"""
from typing import Callable, List, Optional, Union

import PIL
import torch
from transformers import (
    CLIPImageProcessor,
    CLIPSegForImageSegmentation,
    CLIPSegProcessor,
    CLIPTextModel,
    CLIPTokenizer,
)

from diffusers import DiffusionPipeline
from diffusers.configuration_utils import FrozenDict
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import deprecate, is_accelerate_available, logging


A:   str								=		logging.get_logger(__name__)  # pylint: disable=invalid-name



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     )  ->      List[Any]:





    '''simple docstring'''




    super().__init__()

    if hasattr(scheduler.config      ,     """steps_offset"""						) and scheduler.config.steps_offset != 1:
     UpperCAmelCase	:					Any	=	(
         F"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
         F" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
         """to update the config accordingly as leaving `steps_offset` might led to incorrect results"""
         """ in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"""
         """ it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"""
         """ file"""
     )
     deprecate("""steps_offset!=1"""      ,     """1.0.0"""      ,     _SCREAMING_SNAKE_CASE      ,     standard_warn=_SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					Tuple	=	dict(scheduler.config						)
     UpperCAmelCase	:					Tuple	=	1
     UpperCAmelCase	:					Tuple	=	FrozenDict(_SCREAMING_SNAKE_CASE						)

    if hasattr(scheduler.config      ,     """skip_prk_steps"""						) and scheduler.config.skip_prk_steps is False:
     UpperCAmelCase	:					Dict	=	(
         F"The configuration file of this scheduler: {scheduler} has not set the configuration"
         """ `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make"""
         """ sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to"""
         """ incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face"""
         """ Hub, it would be very nice if you could open a Pull request for the"""
         """ `scheduler/scheduler_config.json` file"""
     )
     deprecate("""skip_prk_steps not set"""      ,     """1.0.0"""      ,     _SCREAMING_SNAKE_CASE      ,     standard_warn=_SCREAMING_SNAKE_CASE						)
     UpperCAmelCase	:					Union[str, Any]	=	dict(scheduler.config						)
     UpperCAmelCase	:					Optional[Any]	=	True
     UpperCAmelCase	:					str	=	FrozenDict(_SCREAMING_SNAKE_CASE						)

    if safety_checker is None:
     logger.warning(
         F"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
         """ that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"""
         """ results in services or applications open to the public. Both the diffusers team and Hugging Face"""
         """ strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"""
         """ it only for use-cases that involve analyzing network behavior or auditing its results. For more"""
         """ information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."""						)

    self.register_modules(
        segmentation_model=_SCREAMING_SNAKE_CASE      ,     segmentation_processor=_SCREAMING_SNAKE_CASE      ,     vae=_SCREAMING_SNAKE_CASE      ,     text_encoder=_SCREAMING_SNAKE_CASE      ,     tokenizer=_SCREAMING_SNAKE_CASE      ,     unet=_SCREAMING_SNAKE_CASE      ,     scheduler=_SCREAMING_SNAKE_CASE      ,     safety_checker=_SCREAMING_SNAKE_CASE      ,     feature_extractor=_SCREAMING_SNAKE_CASE      ,     )

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE = "auto"						)  ->      List[str]:





    '''simple docstring'''




    if slice_size == "auto":
     # half the attention head size is usually a good trade-off between
     # speed and memory
     UpperCAmelCase	:					List[Any]	=	self.unet.config.attention_head_dim // 2
    self.unet.set_attention_slice(_SCREAMING_SNAKE_CASE						)

   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      str:





    '''simple docstring'''




    self.enable_attention_slicing(_SCREAMING_SNAKE_CASE						)

   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      Tuple:





    '''simple docstring'''




    if is_accelerate_available():
     from accelerate import cpu_offload
    else:
     raise ImportError("""Please install accelerate via `pip install accelerate`"""						)

    UpperCAmelCase	:					List[str]	=	torch.device("""cuda"""						)

    for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]:
     if cpu_offloaded_model is not None:
      cpu_offload(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)

   @property
   # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      Union[str, Any]:





    '''simple docstring'''




    if self.device != torch.device("""meta"""						) or not hasattr(self.unet      ,     """_hf_hook"""						):
     return self.device
    for module in self.unet.modules():
     if (
         hasattr(_SCREAMING_SNAKE_CASE      ,     """_hf_hook"""						)
         and hasattr(module._hf_hook      ,     """execution_device"""						)
         and module._hf_hook.execution_device is not None
     ):
      return torch.device(module._hf_hook.execution_device						)
    return self.device




   @torch.no_grad()
   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE = 512      ,     _SCREAMING_SNAKE_CASE = 512      ,     _SCREAMING_SNAKE_CASE = 50      ,     _SCREAMING_SNAKE_CASE = 7.5      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = 1      ,     _SCREAMING_SNAKE_CASE = 0.0      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = "pil"      ,     _SCREAMING_SNAKE_CASE = True      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = 1      ,     **_SCREAMING_SNAKE_CASE      ,     )  ->      Optional[int]:





    '''simple docstring'''




    UpperCAmelCase	:					List[str]	=	self.segmentation_processor(
        text=[text]      ,     images=[image]      ,     padding="""max_length"""      ,     return_tensors="""pt"""						).to(self.device						)
    UpperCAmelCase	:					str	=	self.segmentation_model(**_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					Optional[Any]	=	torch.sigmoid(outputs.logits						).cpu().detach().unsqueeze(-1						).numpy()
    UpperCAmelCase	:					Optional[Any]	=	self.numpy_to_pil(_SCREAMING_SNAKE_CASE						)[0].resize(image.size						)

    # Run inpainting pipeline with the generated mask
    UpperCAmelCase	:					Tuple	=	StableDiffusionInpaintPipeline(
        vae=self.vae      ,     text_encoder=self.text_encoder      ,     tokenizer=self.tokenizer      ,     unet=self.unet      ,     scheduler=self.scheduler      ,     safety_checker=self.safety_checker      ,     feature_extractor=self.feature_extractor      ,     )
    return inpainting_pipeline(
        prompt=_SCREAMING_SNAKE_CASE      ,     image=_SCREAMING_SNAKE_CASE      ,     mask_image=_SCREAMING_SNAKE_CASE      ,     height=_SCREAMING_SNAKE_CASE      ,     width=_SCREAMING_SNAKE_CASE      ,     num_inference_steps=_SCREAMING_SNAKE_CASE      ,     guidance_scale=_SCREAMING_SNAKE_CASE      ,     negative_prompt=_SCREAMING_SNAKE_CASE      ,     num_images_per_prompt=_SCREAMING_SNAKE_CASE      ,     eta=_SCREAMING_SNAKE_CASE      ,     generator=_SCREAMING_SNAKE_CASE      ,     latents=_SCREAMING_SNAKE_CASE      ,     output_type=_SCREAMING_SNAKE_CASE      ,     return_dict=_SCREAMING_SNAKE_CASE      ,     callback=_SCREAMING_SNAKE_CASE      ,     callback_steps=_SCREAMING_SNAKE_CASE      ,     )







import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    TextToVideoSDPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, load_numpy, skip_mps, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

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


enable_full_determinism()

@skip_mps
class 		UpperCamelCase__ (      lowerCAmelCase_							,      unittest.TestCase   ):



     '''simple docstring'''

     __snake_case    :	List[str]			=			TextToVideoSDPipeline
     __snake_case    :	int			=			TEXT_TO_IMAGE_PARAMS
     __snake_case    :	Tuple			=			TEXT_TO_IMAGE_BATCH_PARAMS
     # No `output_type`.
     __snake_case    :	Dict			=			frozenset(
         [
             "num_inference_steps",
             "generator",
             "latents",
             "return_dict",
             "callback",
             "callback_steps",
         ]   )






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




           '''simple docstring'''


           torch.manual_seed(0       )
           SCREAMING_SNAKE_CASE		=						UNetaDConditionModel(
               block_out_channels=(32, 64, 64, 64)						,layers_per_block=2						,sample_size=32						,in_channels=4						,out_channels=4						,down_block_types=("""CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """CrossAttnDownBlock3D""", """DownBlock3D""")						,up_block_types=("""UpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""", """CrossAttnUpBlock3D""")						,cross_attention_dim=32						,attention_head_dim=4						,)
           SCREAMING_SNAKE_CASE		=						DDIMScheduler(
               beta_start=0.00085						,beta_end=0.012						,beta_schedule="""scaled_linear"""						,clip_sample=lowerCamelCase__						,set_alpha_to_one=lowerCamelCase__						,)
           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						,sample_size=128						,)
           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						,hidden_act="""gelu"""						,projection_dim=512						,)
           SCREAMING_SNAKE_CASE		=						CLIPTextModel(lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""       )

           SCREAMING_SNAKE_CASE		=						{
               """unet""": unet,
               """scheduler""": scheduler,
               """vae""": vae,
               """text_encoder""": text_encoder,
               """tokenizer""": tokenizer,
           }
           return components






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




           '''simple docstring'''


           if str(lowerCamelCase__       ).startswith("""mps"""       ):
                 SCREAMING_SNAKE_CASE		=						torch.manual_seed(lowerCamelCase__       )
           else:
                 SCREAMING_SNAKE_CASE		=						torch.Generator(device=lowerCamelCase__       ).manual_seed(lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						{
               """prompt""": """A painting of a squirrel eating a burger""",
               """generator""": generator,
               """num_inference_steps""": 2,
               """guidance_scale""": 6.0,
               """output_type""": """pt""",
           }
           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		=						TextToVideoSDPipeline(**lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						sd_pipe.to(lowerCamelCase__       )
           sd_pipe.set_progress_bar_config(disable=lowerCamelCase__       )

           SCREAMING_SNAKE_CASE		=						self.get_dummy_inputs(lowerCamelCase__       )
           SCREAMING_SNAKE_CASE		=						"""np"""
           SCREAMING_SNAKE_CASE		=						sd_pipe(**lowerCamelCase__       ).frames
           SCREAMING_SNAKE_CASE		=						frames[0][-3:, -3:, -1]

           assert frames[0].shape == (64, 64, 3)
           SCREAMING_SNAKE_CASE		=						np.array([158.0, 160.0, 153.0, 125.0, 100.0, 121.0, 111.0, 93.0, 113.0]       )

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






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Dict       )     ->		int:




           '''simple docstring'''


           self._test_attention_slicing_forward_pass(test_mean_pixel_difference=lowerCamelCase__						,expected_max_diff=3e-3       )






     @unittest.skipIf(
         torch_device != """cuda""" or not is_xformers_available()						,reason="""XFormers attention is only available with CUDA and `xformers` installed"""						,)
     def 				SCREAMING_SNAKE_CASE__  (							self						:    Tuple       )     ->		Any:




           '''simple docstring'''


           self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=lowerCamelCase__						,expected_max_diff=1e-2       )






     @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""       )
     def 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[Any]       )     ->		List[Any]:




           '''simple docstring'''


           pass






     @unittest.skip(reason="""Batching needs to be properly figured out first for this pipeline."""       )
     def 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[Any]       )     ->		Any:




           '''simple docstring'''


           pass






     @unittest.skip(reason="""`num_images_per_prompt` argument is not supported for this pipeline."""       )
     def 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[int]       )     ->		Tuple:




           '''simple docstring'''


           pass






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




           '''simple docstring'''


           return super().test_progress_bar()

@slow
@skip_mps
class 		UpperCamelCase__ (      unittest.TestCase   ):



     '''simple docstring'''

     def 				SCREAMING_SNAKE_CASE__  (							self						:    Any       )     ->		Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						load_numpy(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video.npy"""       )

           SCREAMING_SNAKE_CASE		=						TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b"""       )
           SCREAMING_SNAKE_CASE		=						DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
           SCREAMING_SNAKE_CASE		=						pipe.to("""cuda"""       )

           SCREAMING_SNAKE_CASE		=						"""Spiderman is surfing"""
           SCREAMING_SNAKE_CASE		=						torch.Generator(device="""cpu"""       ).manual_seed(0       )

           SCREAMING_SNAKE_CASE		=						pipe(lowerCamelCase__						,generator=lowerCamelCase__						,num_inference_steps=25						,output_type="""pt"""       ).frames
           SCREAMING_SNAKE_CASE		=						video_frames.cpu().numpy()

           assert np.abs(expected_video - video       ).mean() < 5e-2






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Any       )     ->		Any:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						load_numpy(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/text_to_video/video_2step.npy"""       )

           SCREAMING_SNAKE_CASE		=						TextToVideoSDPipeline.from_pretrained("""damo-vilab/text-to-video-ms-1.7b"""       )
           SCREAMING_SNAKE_CASE		=						pipe.to("""cuda"""       )

           SCREAMING_SNAKE_CASE		=						"""Spiderman is surfing"""
           SCREAMING_SNAKE_CASE		=						torch.Generator(device="""cpu"""       ).manual_seed(0       )

           SCREAMING_SNAKE_CASE		=						pipe(lowerCamelCase__						,generator=lowerCamelCase__						,num_inference_steps=2						,output_type="""pt"""       ).frames
           SCREAMING_SNAKE_CASE		=						video_frames.cpu().numpy()

           assert np.abs(expected_video - video       ).mean() < 5e-2


