




import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    UNetaDConditionModel,
    VideoToVideoSDPipeline,
)
from diffusers.utils import floats_tensor, is_xformers_available, skip_mps
from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()





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




    """simple docstring"""

    snake_case__   = VideoToVideoSDPipeline
    snake_case__   = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"}       ) - {"image", "width", "height"}
    snake_case__   = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"}       ) - {"image"}
    snake_case__   = PipelineTesterMixin.required_optional_params - {"latents"}
    snake_case__   = False

    # No `output_type`.
    snake_case__   = frozenset(
        [
            "num_inference_steps",
            "generator",
            "latents",
            "return_dict",
            "callback",
            "callback_steps",
        ]       )


    def   a (			self	:	int  ) ->			Optional[int]:
         torch.manual_seed(0  )
         lowerCAmelCase__            =					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  ,      )
         lowerCAmelCase__            =					DDIMScheduler(
             beta_start=0.00_085  ,      beta_end=0.012  ,      beta_schedule="scaled_linear"  ,      clip_sample=SCREAMING_SNAKE_CASE__  ,      set_alpha_to_one=SCREAMING_SNAKE_CASE__  ,      )
         torch.manual_seed(0  )
         lowerCAmelCase__            =					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  )
         lowerCAmelCase__            =					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  ,      hidden_act="gelu"  ,      projection_dim=512  ,      )
         lowerCAmelCase__            =					CLIPTextModel(SCREAMING_SNAKE_CASE__  )
         lowerCAmelCase__            =					CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"  )

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


    def   a (			self	:	Tuple  ,      SCREAMING_SNAKE_CASE__	:	int  ,      SCREAMING_SNAKE_CASE__	:	Dict=0  ) ->			Tuple:
         # 3 frames
         lowerCAmelCase__            =					floats_tensor((1, 3, 3, 32, 32)  ,      rng=random.Random(SCREAMING_SNAKE_CASE__  )  ).to(SCREAMING_SNAKE_CASE__  )

         if str(SCREAMING_SNAKE_CASE__  ).startswith("mps"  ):
              lowerCAmelCase__            =					torch.manual_seed(SCREAMING_SNAKE_CASE__  )
         else:
              lowerCAmelCase__            =					torch.Generator(device=SCREAMING_SNAKE_CASE__  ).manual_seed(SCREAMING_SNAKE_CASE__  )
         lowerCAmelCase__            =					{
             "prompt": "A painting of a squirrel eating a burger",
             "video": video,
             "generator": generator,
             "num_inference_steps": 2,
             "guidance_scale": 6.0,
             "output_type": "pt",
         }
         return inputs


    def   a (			self	:	Union[str, Any]  ) ->			str:
         lowerCAmelCase__            =					"cpu"  # ensure determinism for the device-dependent torch.Generator
         lowerCAmelCase__            =					self.get_dummy_components()
         lowerCAmelCase__            =					VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE__  )
         lowerCAmelCase__            =					sd_pipe.to(SCREAMING_SNAKE_CASE__  )
         sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__  )

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

         assert frames[0].shape == (32, 32, 3)
         lowerCAmelCase__            =					np.array([106, 117, 113, 174, 137, 112, 148, 151, 131]  )

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


    @unittest.skipIf(
        torch_device != "cuda" or not is_xformers_available()  ,      reason="XFormers attention is only available with CUDA and `xformers` installed"  ,      )
    def   a (			self	:	List[Any]  ) ->			str:
         self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE__  ,      expected_max_diff=5e-3  )


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


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


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


    def   a (			self	:	Optional[Any]  ) ->			Tuple:
         return super().test_progress_bar()






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




    """simple docstring"""

    def   a (			self	:	str  ) ->			int:
         lowerCAmelCase__            =					VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL"  ,      torch_dtype=torch.floataa  )
         pipe.enable_model_cpu_offload()

         # 10 frames
         lowerCAmelCase__            =					torch.Generator(device="cpu"  ).manual_seed(0  )
         lowerCAmelCase__            =					torch.randn((1, 10, 3, 1_024, 576)  ,      generator=SCREAMING_SNAKE_CASE__  )
         lowerCAmelCase__            =					video.to("cuda"  )

         lowerCAmelCase__            =					"Spiderman is surfing"

         lowerCAmelCase__            =					pipe(SCREAMING_SNAKE_CASE__  ,      video=SCREAMING_SNAKE_CASE__  ,      generator=SCREAMING_SNAKE_CASE__  ,      num_inference_steps=3  ,      output_type="pt"  ).frames

         lowerCAmelCase__            =					np.array([-1.0_458_984, -1.1_279_297, -0.9_663_086, -0.91_503_906, -0.75_097_656]  )
         assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array  ).sum() < 1e-2






'''simple docstring'''







import numpy as np
from cva import COLOR_BGR2GRAY, cvtColor, imread
from numpy import array, uinta
from PIL import Image

from digital_image_processing import change_contrast as cc
from digital_image_processing import convert_to_negative as cn
from digital_image_processing import sepia as sp
from digital_image_processing.dithering import burkes as bs
from digital_image_processing.edge_detection import canny
from digital_image_processing.filters import convolve as conv
from digital_image_processing.filters import gaussian_filter as gg
from digital_image_processing.filters import local_binary_pattern as lbp
from digital_image_processing.filters import median_filter as med
from digital_image_processing.filters import sobel_filter as sob
from digital_image_processing.resize import resize as rs

lowercase      :   Any      =       imread(R"""digital_image_processing/image_data/lena_small.jpg""")
lowercase      :   List[str]      =       cvtColor(img, COLOR_BGR2GRAY)



def        lowerCamelCase__				(      ):
     snake_case			:      Optional[int]        =			cn.convert_to_negative(__lowercase				)
     # assert negative_img array for at least one True
     assert negative_img.any()



def        lowerCamelCase__				(      ):
     with Image.open("""digital_image_processing/image_data/lena_small.jpg"""				) as img:
          # Work around assertion for response
          assert str(cc.change_contrast(__lowercase     ,   110				)				).startswith(
              """<PIL.Image.Image image mode=RGB size=100x100 at"""				)



def        lowerCamelCase__				(      ):
     snake_case			:      Union[str, Any]        =			canny.gen_gaussian_kernel(9     ,   sigma=1.4				)
     # Assert ambiguous array
     assert resp.all()



def        lowerCamelCase__				(      ):
     snake_case			:      Optional[Any]        =			imread("""digital_image_processing/image_data/lena_small.jpg"""     ,   0				)
     # assert ambiguous array for all == True
     assert canny_img.all()
     snake_case			:      Any        =			canny.canny(__lowercase				)
     # assert canny array for at least one True
     assert canny_array.any()



def        lowerCamelCase__				(      ):
     assert gg.gaussian_filter(__lowercase     ,   5     ,   sigma=0.9				).all()



def        lowerCamelCase__				(      ):
     # laplace diagonals
     snake_case			:      int        =			array([[0.25, 0.5, 0.25], [0.5, -3, 0.5], [0.25, 0.5, 0.25]]				)
     snake_case			:      Tuple        =			conv.img_convolve(__lowercase     ,   __lowercase				).astype(__lowercase				)
     assert res.any()



def        lowerCamelCase__				(      ):
     assert med.median_filter(__lowercase     ,   3				).any()



def        lowerCamelCase__				(      ):
     snake_case ,		snake_case			:      Dict        =			sob.sobel_filter(__lowercase				)
     assert grad.any() and theta.any()



def        lowerCamelCase__				(      ):
     snake_case			:      int        =			sp.make_sepia(__lowercase     ,   20				)
     assert sepia.all()



def        lowerCamelCase__				(      __lowercase = "digital_image_processing/image_data/lena_small.jpg"				):
     snake_case			:      int        =			bs.Burkes(imread(__lowercase     ,   1				)     ,   120				)
     burkes.process()
     assert burkes.output_img.any()



def        lowerCamelCase__				(      __lowercase = "digital_image_processing/image_data/lena_small.jpg"     ,   ):
     snake_case			:      Dict        =			rs.NearestNeighbour(imread(__lowercase     ,   1				)     ,   400     ,   200				)
     nn.process()
     assert nn.output.any()







def        lowerCamelCase__				(      ):
     snake_case			:      int        =			"""digital_image_processing/image_data/lena.jpg"""

     # Reading the image and converting it to grayscale.
     snake_case			:      Tuple        =			imread(__lowercase     ,   0				)

     # Test for get_neighbors_pixel function() return not None
     snake_case			:      Optional[int]        =			0
     snake_case			:      Tuple        =			0
     snake_case			:      Any        =			image[x_coordinate][y_coordinate]

     snake_case			:      Any        =			lbp.get_neighbors_pixel(
         __lowercase     ,   __lowercase     ,   __lowercase     ,   __lowercase				)

     assert neighbors_pixels is not None

     # Test for local_binary_pattern function()
     # Create a numpy array as the same height and width of read image
     snake_case			:      List[Any]        =			np.zeros((image.shape[0], image.shape[1])				)

     # Iterating through the image and calculating the local binary pattern value
     # for each pixel.
     for i in range(0     ,   image.shape[0]				):
          for j in range(0     ,   image.shape[1]				):
               snake_case			:      Optional[Any]        =			lbp.local_binary_value(__lowercase     ,   __lowercase     ,   __lowercase				)

     assert lbp_image.any()



