"""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 					UpperCAmelCase		(unittest.TestCase						):



    """simple docstring"""

    def _snake_case    (     self							):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()






    @property
    def _snake_case    (     self							):
       lowercase__:     List[str]      =   1
       lowercase__:     Optional[int]      =   3
       lowercase__:     List[str]      =   (32, 32)

       lowercase__:     List[Any]      =   floats_tensor((batch_size, num_channels) + sizes					,    rng=random.Random(0							)							).to(_UpperCAmelCase							)
       return image






    @property
    def _snake_case    (     self							):
       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 _snake_case    (     self							):
       torch.manual_seed(0							)
       lowercase__:     Tuple      =   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 _snake_case    (     self							):
       torch.manual_seed(0							)
       lowercase__:     Optional[Any]      =   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					,    )
       return CLIPTextModel(_UpperCAmelCase							)






    @property
    def _snake_case    (     self							):
       def extract(*_UpperCAmelCase					,    **_UpperCAmelCase							):


          class 					UpperCAmelCase		:



              """simple docstring"""

              def __init__(     self							):
                 lowercase__:     List[str]      =   torch.ones([0]							)






              def _snake_case    (     self					,    _UpperCAmelCase							):
                 self.pixel_values.to(_UpperCAmelCase							)
                 return self



          return Out()

       return extract






    def _snake_case    (     self							):
       lowercase__:     List[Any]      =   '''cpu'''  # ensure determinism for the device-dependent torch.Generator
       lowercase__:     Optional[Any]      =   self.dummy_cond_unet
       lowercase__:     Any      =   DDIMScheduler(
           beta_start=0.00_085					,    beta_end=0.012					,    beta_schedule='''scaled_linear'''					,    clip_sample=_UpperCAmelCase					,    set_alpha_to_one=_UpperCAmelCase					,    )

       lowercase__:     Any      =   self.dummy_vae
       lowercase__:     Dict      =   self.dummy_text_encoder
       lowercase__:     Tuple      =   CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							)

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

       lowercase__:     Union[str, Any]      =   '''A painting of a squirrel eating a burger'''

       lowercase__:     Optional[int]      =   torch.Generator(device=_UpperCAmelCase							).manual_seed(0							)
       lowercase__:     List[Any]      =   sd_pipe([prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=6.0					,    num_inference_steps=2					,    output_type='''np'''							)
       lowercase__:     List[Any]      =   output.images

       lowercase__:     List[Any]      =   torch.Generator(device=_UpperCAmelCase							).manual_seed(0							)
       lowercase__:     Optional[Any]      =   sd_pipe(
           [prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=6.0					,    num_inference_steps=2					,    output_type='''np'''					,    return_dict=_UpperCAmelCase					,    )[0]

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

       assert image.shape == (1, 64, 64, 3)
       lowercase__:     List[str]      =   np.array([0.5_753, 0.6_114, 0.5_001, 0.5_034, 0.5_470, 0.4_729, 0.4_971, 0.4_867, 0.4_867]							)

       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 _snake_case    (     self							):
       lowercase__:     List[str]      =   '''cpu'''  # ensure determinism for the device-dependent torch.Generator
       lowercase__:     Dict      =   self.dummy_cond_unet
       lowercase__:     Optional[Any]      =   PNDMScheduler(skip_prk_steps=_UpperCAmelCase							)
       lowercase__:     str      =   self.dummy_vae
       lowercase__:     List[str]      =   self.dummy_text_encoder
       lowercase__:     Any      =   CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							)

       # make sure here that pndm scheduler skips prk
       lowercase__:     List[str]      =   StableDiffusionPipeline(
           unet=_UpperCAmelCase					,    scheduler=_UpperCAmelCase					,    vae=_UpperCAmelCase					,    text_encoder=_UpperCAmelCase					,    tokenizer=_UpperCAmelCase					,    safety_checker=_UpperCAmelCase					,    feature_extractor=self.dummy_extractor					,    )
       lowercase__:     Optional[int]      =   sd_pipe.to(_UpperCAmelCase							)
       sd_pipe.set_progress_bar_config(disable=_UpperCAmelCase							)

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

       lowercase__:     Optional[Any]      =   output.images

       lowercase__:     List[Any]      =   torch.Generator(device=_UpperCAmelCase							).manual_seed(0							)
       lowercase__:     Dict      =   sd_pipe(
           [prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=6.0					,    num_inference_steps=2					,    output_type='''np'''					,    return_dict=_UpperCAmelCase					,    )[0]

       lowercase__:     Optional[int]      =   image[0, -3:, -3:, -1]
       lowercase__:     Optional[int]      =   image_from_tuple[0, -3:, -3:, -1]

       assert image.shape == (1, 64, 64, 3)
       lowercase__:     List[str]      =   np.array([0.5_122, 0.5_712, 0.4_825, 0.5_053, 0.5_646, 0.4_769, 0.5_179, 0.4_894, 0.4_994]							)

       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 _snake_case    (     self							):
       lowercase__:     Union[str, Any]      =   StableDiffusionPipeline.from_pretrained(
           '''hf-internal-testing/tiny-stable-diffusion-lms-pipe'''					,    safety_checker=_UpperCAmelCase							)
       assert isinstance(_UpperCAmelCase					,    _UpperCAmelCase							)
       assert isinstance(pipe.scheduler					,    _UpperCAmelCase							)
       assert pipe.safety_checker is None

       lowercase__:     Tuple      =   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(_UpperCAmelCase							)
          lowercase__:     Union[str, Any]      =   StableDiffusionPipeline.from_pretrained(_UpperCAmelCase							)

       # sanity check that the pipeline still works
       assert pipe.safety_checker is None
       lowercase__:     Optional[Any]      =   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 _snake_case    (     self							):
       lowercase__:     Optional[Any]      =   self.dummy_cond_unet
       lowercase__:     List[str]      =   PNDMScheduler(skip_prk_steps=_UpperCAmelCase							)
       lowercase__:     Optional[int]      =   self.dummy_vae
       lowercase__:     Optional[int]      =   self.dummy_text_encoder
       lowercase__:     int      =   CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							)

       # put models in fp16
       lowercase__:     str      =   unet.half()
       lowercase__:     Dict      =   vae.half()
       lowercase__:     Dict      =   bert.half()

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

       lowercase__:     Tuple      =   '''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 					UpperCAmelCase		(unittest.TestCase						):



    """simple docstring"""

    def _snake_case    (     self							):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()






    def _snake_case    (     self							):
       lowercase__:     Any      =   '''cuda'''
       lowercase__:     int      =   StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''							)
       lowercase__:     int      =   pipe.to(_UpperCAmelCase							)
       pipe.set_progress_bar_config(disable=_UpperCAmelCase							)

       lowercase__:     Union[str, Any]      =   '''a photo of a cat'''
       lowercase__:     Optional[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__:     Optional[int]      =   3
       lowercase__:     List[str]      =   7

       # no sega enabled
       lowercase__:     List[Any]      =   torch.Generator(_UpperCAmelCase							)
       generator.manual_seed(_UpperCAmelCase							)
       lowercase__:     Dict      =   pipe(
           [prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=_UpperCAmelCase					,    num_inference_steps=50					,    output_type='''np'''					,    width=512					,    height=512					,    )

       lowercase__:     Tuple      =   output.images
       lowercase__:     Any      =   image[0, -3:, -3:, -1]
       lowercase__:     Any      =   [
           0.34_673_113,
           0.38_492_733,
           0.37_597_352,
           0.34_086_335,
           0.35_650_748,
           0.35_579_205,
           0.3_384_763,
           0.34_340_236,
           0.3_573_271,
       ]

       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(_UpperCAmelCase							)
       lowercase__:     Dict      =   pipe(
           [prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=_UpperCAmelCase					,    num_inference_steps=50					,    output_type='''np'''					,    width=512					,    height=512					,    **_UpperCAmelCase					,    )

       lowercase__:     int      =   output.images
       lowercase__:     Any      =   image[0, -3:, -3:, -1]
       lowercase__:     Union[str, Any]      =   [
           0.41_887_826,
           0.37_728_766,
           0.30_138_272,
           0.41_416_335,
           0.41_664_985,
           0.36_283_392,
           0.36_191_246,
           0.43_364_465,
           0.43_001_732,
       ]

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

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






    def _snake_case    (     self							):
       lowercase__:     Optional[int]      =   '''cuda'''
       lowercase__:     Tuple      =   StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''							)
       lowercase__:     Any      =   pipe.to(_UpperCAmelCase							)
       pipe.set_progress_bar_config(disable=_UpperCAmelCase							)

       lowercase__:     List[str]      =   '''an image of a crowded boulevard, realistic, 4k'''
       lowercase__:     List[str]      =   {
           '''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__:     List[Any]      =   9
       lowercase__:     Union[str, Any]      =   7

       # no sega enabled
       lowercase__:     Dict      =   torch.Generator(_UpperCAmelCase							)
       generator.manual_seed(_UpperCAmelCase							)
       lowercase__:     Dict      =   pipe(
           [prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=_UpperCAmelCase					,    num_inference_steps=50					,    output_type='''np'''					,    width=512					,    height=512					,    )

       lowercase__:     str      =   output.images
       lowercase__:     Union[str, Any]      =   image[0, -3:, -3:, -1]
       lowercase__:     int      =   [
           0.43_497_998,
           0.91_814_065,
           0.7_540_739,
           0.55_580_205,
           0.8_467_265,
           0.5_389_691,
           0.62_574_506,
           0.58_897_763,
           0.50_926_757,
       ]

       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(_UpperCAmelCase							)
       lowercase__:     List[Any]      =   pipe(
           [prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=_UpperCAmelCase					,    num_inference_steps=50					,    output_type='''np'''					,    width=512					,    height=512					,    **_UpperCAmelCase					,    )

       lowercase__:     str      =   output.images
       lowercase__:     Optional[Any]      =   image[0, -3:, -3:, -1]
       lowercase__:     Optional[Any]      =   [
           0.3_089_719,
           0.30_500_144,
           0.29_016_042,
           0.30_630_964,
           0.325_687,
           0.29_419_225,
           0.2_908_091,
           0.28_723_598,
           0.27_696_294,
       ]

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

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






    def _snake_case    (     self							):
       lowercase__:     Optional[int]      =   '''cuda'''
       lowercase__:     Tuple      =   StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''							)
       lowercase__:     Optional[Any]      =   pipe.to(_UpperCAmelCase							)
       pipe.set_progress_bar_config(disable=_UpperCAmelCase							)

       lowercase__:     Union[str, Any]      =   '''a castle next to a river'''
       lowercase__:     List[str]      =   {
           '''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[str]      =   7

       # no sega enabled
       lowercase__:     Dict      =   torch.Generator(_UpperCAmelCase							)
       generator.manual_seed(_UpperCAmelCase							)
       lowercase__:     str      =   pipe(
           [prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=_UpperCAmelCase					,    num_inference_steps=50					,    output_type='''np'''					,    width=512					,    height=512					,    )

       lowercase__:     Union[str, Any]      =   output.images
       lowercase__:     Union[str, Any]      =   image[0, -3:, -3:, -1]
       lowercase__:     Dict      =   [
           0.75_163_555,
           0.76_037_145,
           0.61_785,
           0.9_189_673,
           0.8_627_701,
           0.85_189_694,
           0.8_512_813,
           0.87_012_076,
           0.8_312_857,
       ]

       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(_UpperCAmelCase							)
       lowercase__:     int      =   pipe(
           [prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=_UpperCAmelCase					,    num_inference_steps=50					,    output_type='''np'''					,    width=512					,    height=512					,    **_UpperCAmelCase					,    )

       lowercase__:     Union[str, Any]      =   output.images
       lowercase__:     Union[str, Any]      =   image[0, -3:, -3:, -1]
       lowercase__:     List[str]      =   [
           0.73_553_365,
           0.7_537_271,
           0.74_341_905,
           0.66_480_356,
           0.6_472_925,
           0.63_039_416,
           0.64_812_905,
           0.6_749_717,
           0.6_517_102,
       ]

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

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






    def _snake_case    (     self							):
       lowercase__:     int      =   '''cuda'''
       lowercase__:     Any      =   StableDiffusionPipeline.from_pretrained('''runwayml/stable-diffusion-v1-5'''					,    torch_dtype=torch.floataa							)
       lowercase__:     List[Any]      =   pipe.to(_UpperCAmelCase							)
       pipe.set_progress_bar_config(disable=_UpperCAmelCase							)

       lowercase__:     Dict      =   '''a photo of a cat'''
       lowercase__:     int      =   {
           '''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__:     Optional[int]      =   7

       # no sega enabled
       lowercase__:     Tuple      =   torch.Generator(_UpperCAmelCase							)
       generator.manual_seed(_UpperCAmelCase							)
       lowercase__:     Tuple      =   pipe(
           [prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=_UpperCAmelCase					,    num_inference_steps=50					,    output_type='''np'''					,    width=512					,    height=512					,    )

       lowercase__:     Dict      =   output.images
       lowercase__:     str      =   image[0, -3:, -3:, -1]
       lowercase__:     Any      =   [
           0.34_887_695,
           0.3_876_953,
           0.375,
           0.34_423_828,
           0.3_581_543,
           0.35_717_773,
           0.3_383_789,
           0.34_570_312,
           0.359_375,
       ]

       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(_UpperCAmelCase							)
       lowercase__:     int      =   pipe(
           [prompt]					,    generator=_UpperCAmelCase					,    guidance_scale=_UpperCAmelCase					,    num_inference_steps=50					,    output_type='''np'''					,    width=512					,    height=512					,    **_UpperCAmelCase					,    )

       lowercase__:     List[str]      =   output.images
       lowercase__:     List[Any]      =   image[0, -3:, -3:, -1]
       lowercase__:     Optional[int]      =   [
           0.42_285_156,
           0.36_914_062,
           0.29_077_148,
           0.42_041_016,
           0.41_918_945,
           0.35_498_047,
           0.3_618_164,
           0.4_423_828,
           0.43_115_234,
       ]

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

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

"""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 SCREAMING_SNAKE_CASE__    (     __UpperCAmelCase ,					__UpperCAmelCase=1_0 ,					__UpperCAmelCase=1_0 ,					__UpperCAmelCase=False ,					__UpperCAmelCase=False				)						->						List[str]:
   lowercase__:     List[Any]      =   []
   for i in range(image_processor_tester.num_frames				):
      video.append(np.random.randint(2_5_5 ,					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
      lowercase__:     Union[str, Any]      =   [Image.fromarray(np.moveaxis(__UpperCAmelCase ,					0 ,					-1				)				) for frame in video]

   if torchify:
      lowercase__:     List[str]      =   [torch.from_numpy(__UpperCAmelCase				) for frame in video]

   return video



def SCREAMING_SNAKE_CASE__    (     __UpperCAmelCase ,					__UpperCAmelCase=False ,					__UpperCAmelCase=False ,					__UpperCAmelCase=False				)						->						Tuple:
   assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

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

   return video_inputs


class 					UpperCAmelCase		(unittest.TestCase						):



    """simple docstring"""

    def __init__(     self					,    _UpperCAmelCase					,    _UpperCAmelCase=7					,    _UpperCAmelCase=3					,    _UpperCAmelCase=4					,    _UpperCAmelCase=18					,    _UpperCAmelCase=30					,    _UpperCAmelCase=400					,    _UpperCAmelCase=True					,    _UpperCAmelCase=None					,    _UpperCAmelCase=True					,    _UpperCAmelCase=[0.5, 0.5, 0.5]					,    _UpperCAmelCase=[0.5, 0.5, 0.5]					,    _UpperCAmelCase=True					,    _UpperCAmelCase=None					,    ):
       lowercase__:     Any      =   size if size is not None else {'''shortest_edge''': 18}
       lowercase__:     List[Any]      =   crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

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






    def _snake_case    (     self							):
       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 					UpperCAmelCase		(_UpperCAmelCase					,unittest.TestCase						):



    """simple docstring"""

    _UpperCAmelCase			:str							=				TvltImageProcessor if is_vision_available() else None






    def _snake_case    (     self							):
       lowercase__:     List[Any]      =   TvltImageProcessorTester(self							)






    @property
    def _snake_case    (     self							):
       return self.image_processor_tester.prepare_image_processor_dict()






    def _snake_case    (     self							):
       lowercase__:     List[str]      =   self.image_processing_class(**self.image_processor_dict							)
       self.assertTrue(hasattr(_UpperCAmelCase					,    '''image_mean'''							)							)
       self.assertTrue(hasattr(_UpperCAmelCase					,    '''image_std'''							)							)
       self.assertTrue(hasattr(_UpperCAmelCase					,    '''do_normalize'''							)							)
       self.assertTrue(hasattr(_UpperCAmelCase					,    '''do_resize'''							)							)
       self.assertTrue(hasattr(_UpperCAmelCase					,    '''do_center_crop'''							)							)
       self.assertTrue(hasattr(_UpperCAmelCase					,    '''size'''							)							)






    def _snake_case    (     self							):
       # Initialize image_processor
       lowercase__:     List[str]      =   self.image_processing_class(**self.image_processor_dict							)
       # create random PIL videos
       lowercase__:     str      =   prepare_video_inputs(self.image_processor_tester					,    equal_resolution=_UpperCAmelCase							)
       for video in video_inputs:
          self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase							)
          self.assertIsInstance(video[0]					,    Image.Image							)

       # Test not batched input
       lowercase__:     Union[str, Any]      =   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
       lowercase__:     Tuple      =   image_processor(_UpperCAmelCase					,    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 _snake_case    (     self							):
       # Initialize image_processor
       lowercase__:     str      =   self.image_processing_class(**self.image_processor_dict							)
       # create random numpy tensors
       lowercase__:     List[str]      =   prepare_video_inputs(self.image_processor_tester					,    equal_resolution=_UpperCAmelCase					,    numpify=_UpperCAmelCase							)
       for video in video_inputs:
          self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase							)
          self.assertIsInstance(video[0]					,    np.ndarray							)

       # Test not batched input
       lowercase__:     Optional[Any]      =   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
       lowercase__:     Tuple      =   image_processor(_UpperCAmelCase					,    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 _snake_case    (     self							):
       # Initialize image_processor
       lowercase__:     List[Any]      =   self.image_processing_class(**self.image_processor_dict							)
       # create random PyTorch tensors
       lowercase__:     Optional[int]      =   prepare_video_inputs(self.image_processor_tester					,    equal_resolution=_UpperCAmelCase					,    torchify=_UpperCAmelCase							)
       for video in video_inputs:
          self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase							)
          self.assertIsInstance(video[0]					,    torch.Tensor							)

       # Test not batched input
       lowercase__:     Optional[Any]      =   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
       lowercase__:     List[Any]      =   image_processor(_UpperCAmelCase					,    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'''],
           )					,    )
