




"""simple docstring"""

import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
							import torch

if is_vision_available():
							from PIL import Image

							from transformers import TvltImageProcessor



def   UpperCamelCase__     (		lowercase__  :     List[str]       ,     lowercase__  :     Union[str, Any]=10       ,     lowercase__  :     Optional[Any]=10       ,     lowercase__  :     str=False       ,     lowercase__  :     Any=False   ):
		snake_case		:						Union[str, Any]								=				[]
		for i in range(image_processor_tester.num_frames   ):
				video.append(np.random.randint(255       ,     size=(image_processor_tester.num_channels, width, height)       ,     dtype=np.uinta   )   )

		if not numpify and not torchify:
				# PIL expects the channel dimension as last dimension
				snake_case		:						List[str]								=				[Image.fromarray(np.moveaxis(lowercase__       ,     0       ,     -1   )   ) for frame in video]

		if torchify:
				snake_case		:						Optional[int]								=				[torch.from_numpy(lowercase__   ) for frame in video]

		return video



def   UpperCamelCase__     (		lowercase__  :     List[Any]       ,     lowercase__  :     Tuple=False       ,     lowercase__  :     Dict=False       ,     lowercase__  :     str=False   ):
		assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

		snake_case		:						List[Any]								=				[]
		for i in range(image_processor_tester.batch_size   ):
				if equal_resolution:
						snake_case		:						Optional[int]								=				image_processor_tester.max_resolution
				else:
						snake_case		:						str								=				np.random.choice(
						    np.arange(image_processor_tester.min_resolution       ,     image_processor_tester.max_resolution   )       ,     2   )
						snake_case		:						List[str]								=				prepare_video(
						    image_processor_tester=lowercase__       ,     width=lowercase__       ,     height=lowercase__       ,     numpify=lowercase__       ,     torchify=lowercase__       ,     )
				video_inputs.append(lowercase__   )

		return video_inputs
class 			lowerCamelCase__    (  unittest.TestCase			):


			def __init__(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE=7				, SCREAMING_SNAKE_CASE=3				, SCREAMING_SNAKE_CASE=4				, SCREAMING_SNAKE_CASE=18				, SCREAMING_SNAKE_CASE=30				, SCREAMING_SNAKE_CASE=400				, SCREAMING_SNAKE_CASE=True				, SCREAMING_SNAKE_CASE=None				, SCREAMING_SNAKE_CASE=True				, SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5]				, SCREAMING_SNAKE_CASE=[0.5, 0.5, 0.5]				, SCREAMING_SNAKE_CASE=True				, SCREAMING_SNAKE_CASE=None				, ):



					"""simple docstring"""







					snake_case		:						List[Any]								=				size if size is not None else {"shortest_edge": 18}
					snake_case		:						Optional[int]								=				crop_size if crop_size is not None else {"height": 18, "width": 18}

					snake_case		:						Tuple								=				parent
					snake_case		:						List[str]								=				batch_size
					snake_case		:						Any								=				num_channels
					snake_case		:						Dict								=				num_frames
					snake_case		:						int								=				image_size
					snake_case		:						Optional[Any]								=				min_resolution
					snake_case		:						Tuple								=				max_resolution
					snake_case		:						Any								=				do_resize
					snake_case		:						Any								=				size
					snake_case		:						Optional[int]								=				do_normalize
					snake_case		:						Union[str, Any]								=				image_mean
					snake_case		:						str								=				image_std
					snake_case		:						List[str]								=				do_center_crop
					snake_case		:						Union[str, Any]								=				crop_size



			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					return {
					    "image_mean": self.image_mean,
					    "image_std": self.image_std,
					    "do_normalize": self.do_normalize,
					    "do_resize": self.do_resize,
					    "size": self.size,
					    "do_center_crop": self.do_center_crop,
					    "crop_size": self.crop_size,
					}







@require_torch
@require_vision
class 			lowerCamelCase__    (  lowerCamelCase_				,  unittest.TestCase			):
			a__ :      List[str]								=     TvltImageProcessor if is_vision_available() else None


			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					snake_case		:						int								=				TvltImageProcessorTester(self							)


			@property
			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					return self.image_processor_tester.prepare_image_processor_dict()


			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					snake_case		:						Optional[Any]								=				self.image_processing_class(**self.image_processor_dict							)
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE				, "image_mean"							)							)
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE				, "image_std"							)							)
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE				, "do_normalize"							)							)
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE				, "do_resize"							)							)
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE				, "do_center_crop"							)							)
					self.assertTrue(hasattr(SCREAMING_SNAKE_CASE				, "size"							)							)


			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					snake_case		:						Dict								=				self.image_processing_class(**self.image_processor_dict							)
					# create random PIL videos
					snake_case		:						List[str]								=				prepare_video_inputs(self.image_processor_tester				, equal_resolution=SCREAMING_SNAKE_CASE							)
					for video in video_inputs:
							self.assertIsInstance(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							)
							self.assertIsInstance(video[0]				, Image.Image							)

					# Test not batched input
					snake_case		:						int								=				image_processor(video_inputs[0]				, return_tensors="pt"							).pixel_values
					self.assertEqual(
					    encoded_videos.shape				, (
					        1,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )				, )

					# Test batched
					snake_case		:						int								=				image_processor(SCREAMING_SNAKE_CASE				, return_tensors="pt"							).pixel_values
					self.assertEqual(
					    encoded_videos.shape				, (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )				, )


			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					snake_case		:						int								=				self.image_processing_class(**self.image_processor_dict							)
					# create random numpy tensors
					snake_case		:						str								=				prepare_video_inputs(self.image_processor_tester				, equal_resolution=SCREAMING_SNAKE_CASE				, numpify=SCREAMING_SNAKE_CASE							)
					for video in video_inputs:
							self.assertIsInstance(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							)
							self.assertIsInstance(video[0]				, np.ndarray							)

					# Test not batched input
					snake_case		:						str								=				image_processor(video_inputs[0]				, return_tensors="pt"							).pixel_values
					self.assertEqual(
					    encoded_videos.shape				, (
					        1,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )				, )

					# Test batched
					snake_case		:						List[Any]								=				image_processor(SCREAMING_SNAKE_CASE				, return_tensors="pt"							).pixel_values
					self.assertEqual(
					    encoded_videos.shape				, (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )				, )



			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					snake_case		:						Dict								=				self.image_processing_class(**self.image_processor_dict							)
					# create random PyTorch tensors
					snake_case		:						Dict								=				prepare_video_inputs(self.image_processor_tester				, equal_resolution=SCREAMING_SNAKE_CASE				, torchify=SCREAMING_SNAKE_CASE							)
					for video in video_inputs:
							self.assertIsInstance(SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE							)
							self.assertIsInstance(video[0]				, torch.Tensor							)

					# Test not batched input
					snake_case		:						List[str]								=				image_processor(video_inputs[0]				, return_tensors="pt"							).pixel_values
					self.assertEqual(
					    encoded_videos.shape				, (
					        1,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )				, )

					# Test batched
					snake_case		:						Optional[Any]								=				image_processor(SCREAMING_SNAKE_CASE				, return_tensors="pt"							).pixel_values
					self.assertEqual(
					    encoded_videos.shape				, (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_frames,
					        self.image_processor_tester.num_channels,
					        self.image_processor_tester.crop_size["height"],
					        self.image_processor_tester.crop_size["width"],
					    )				, )






"""simple docstring"""

import gc
import unittest

import numpy as np
import torch

from diffusers import RePaintPipeline, RePaintScheduler, UNetaDModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_image,
    load_numpy,
    nightly,
    require_torch_gpu,
    skip_mps,
    torch_device,
)

from ..pipeline_params import IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class 			lowerCamelCase__    (  lowerCamelCase_				,  unittest.TestCase			):
			a__ :      Optional[Any]								=     RePaintPipeline
			a__ :      List[Any]								=     IMAGE_INPAINTING_PARAMS - {"""width""", """height""", """guidance_scale"""}
			a__ :      List[Any]								=     PipelineTesterMixin.required_optional_params - {
			    """latents""",
			    """num_images_per_prompt""",
			    """callback""",
			    """callback_steps""",
			}
			a__ :      List[Any]								=     IMAGE_INPAINTING_BATCH_PARAMS
			a__ :      List[str]								=     False


			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					torch.manual_seed(0							)
					torch.manual_seed(0							)
					snake_case		:						Union[str, Any]								=				UNetaDModel(
					    block_out_channels=(32, 64)				, layers_per_block=2				, sample_size=32				, in_channels=3				, out_channels=3				, down_block_types=("DownBlock2D", "AttnDownBlock2D")				, up_block_types=("AttnUpBlock2D", "UpBlock2D")				, )
					snake_case		:						Union[str, Any]								=				RePaintScheduler()
					snake_case		:						Optional[Any]								=				{"unet": unet, "scheduler": scheduler}
					return components


			def 							lowerCamelCase_				(     self				, SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE=0							):



					"""simple docstring"""







					if str(SCREAMING_SNAKE_CASE							).startswith("mps"							):
							snake_case		:						str								=				torch.manual_seed(SCREAMING_SNAKE_CASE							)
					else:
							snake_case		:						List[Any]								=				torch.Generator(device=SCREAMING_SNAKE_CASE							).manual_seed(SCREAMING_SNAKE_CASE							)
					snake_case		:						Any								=				np.random.RandomState(SCREAMING_SNAKE_CASE							).standard_normal((1, 3, 32, 32)							)
					snake_case		:						Any								=				torch.from_numpy(SCREAMING_SNAKE_CASE							).to(device=SCREAMING_SNAKE_CASE				, dtype=torch.floataa							)
					snake_case		:						List[str]								=				(image > 0).to(device=SCREAMING_SNAKE_CASE				, dtype=torch.floataa							)
					snake_case		:						int								=				{
					    "image": image,
					    "mask_image": mask,
					    "generator": generator,
					    "num_inference_steps": 5,
					    "eta": 0.0,
					    "jump_length": 2,
					    "jump_n_sample": 2,
					    "output_type": "numpy",
					}
					return inputs


			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					snake_case		:						List[Any]								=				"cpu"  # ensure determinism for the device-dependent torch.Generator
					snake_case		:						Any								=				self.get_dummy_components()
					snake_case		:						Optional[int]								=				RePaintPipeline(**SCREAMING_SNAKE_CASE							)
					snake_case		:						Optional[Any]								=				sd_pipe.to(SCREAMING_SNAKE_CASE							)
					sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE							)

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

					assert image.shape == (1, 32, 32, 3)
					snake_case		:						List[str]								=				np.array([1.00_00, 0.54_26, 0.54_97, 0.22_00, 1.00_00, 1.00_00, 0.56_23, 1.00_00, 0.62_74]							)

					assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-3


			@skip_mps
			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					return super().test_save_load_local()


			@unittest.skip("non-deterministic pipeline"							)
			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					return super().test_inference_batch_single_identical()


			@skip_mps
			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					return super().test_dict_tuple_outputs_equivalent()


			@skip_mps
			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					return super().test_save_load_optional_components()



			@skip_mps
			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					return super().test_attention_slicing_forward_pass()







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


			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







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



			def 							lowerCamelCase_				(     self							):



					"""simple docstring"""







					snake_case		:						Optional[int]								=				load_image(
					    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/"
					    "repaint/celeba_hq_256.png"							)
					snake_case		:						Any								=				load_image(
					    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/mask_256.png"							)
					snake_case		:						List[Any]								=				load_numpy(
					    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/"
					    "repaint/celeba_hq_256_result.npy"							)

					snake_case		:						str								=				"google/ddpm-ema-celebahq-256"
					snake_case		:						Optional[Any]								=				UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE							)
					snake_case		:						Optional[int]								=				RePaintScheduler.from_pretrained(SCREAMING_SNAKE_CASE							)

					snake_case		:						str								=				RePaintPipeline(unet=SCREAMING_SNAKE_CASE				, scheduler=SCREAMING_SNAKE_CASE							).to(SCREAMING_SNAKE_CASE							)
					repaint.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE							)
					repaint.enable_attention_slicing()

					snake_case		:						Union[str, Any]								=				torch.manual_seed(0							)
					snake_case		:						int								=				repaint(
					    SCREAMING_SNAKE_CASE				, SCREAMING_SNAKE_CASE				, num_inference_steps=250				, eta=0.0				, jump_length=10				, jump_n_sample=10				, generator=SCREAMING_SNAKE_CASE				, output_type="np"				, )
					snake_case		:						List[Any]								=				output.images[0]

					assert image.shape == (256, 256, 3)
					assert np.abs(expected_image - image							).mean() < 1E-2

