"""simple docstring"""






from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


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

__A         =				"\n    Examples:\n        ```py\n        >>> import torch\n        >>> import numpy as np\n\n        >>> from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline\n        >>> from transformers import pipeline\n        >>> from diffusers.utils import load_image\n\n\n        >>> def make_hint(image, depth_estimator):\n        ...     image = depth_estimator(image)[\"depth\"]\n        ...     image = np.array(image)\n        ...     image = image[:, :, None]\n        ...     image = np.concatenate([image, image, image], axis=2)\n        ...     detected_map = torch.from_numpy(image).float() / 255.0\n        ...     hint = detected_map.permute(2, 0, 1)\n        ...     return hint\n\n\n        >>> depth_estimator = pipeline(\"depth-estimation\")\n\n        >>> pipe_prior = KandinskyV22PriorEmb2EmbPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior = pipe_prior.to(\"cuda\")\n\n        >>> pipe = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16\n        ... )\n        >>> pipe = pipe.to(\"cuda\")\n\n        >>> img = load_image(\n        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n        ...     \"/kandinsky/cat.png\"\n        ... ).resize((768, 768))\n\n\n        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")\n\n        >>> prompt = \"A robot, 4k photo\"\n        >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"\n\n        >>> generator = torch.Generator(device=\"cuda\").manual_seed(43)\n\n        >>> img_emb = pipe_prior(prompt=prompt, image=img, strength=0.85, generator=generator)\n        >>> negative_emb = pipe_prior(prompt=negative_prior_prompt, image=img, strength=1, generator=generator)\n\n        >>> images = pipe(\n        ...     image=img,\n        ...     strength=0.5,\n        ...     image_embeds=img_emb.image_embeds,\n        ...     negative_image_embeds=negative_emb.image_embeds,\n        ...     hint=hint,\n        ...     num_inference_steps=50,\n        ...     generator=generator,\n        ...     height=768,\n        ...     width=768,\n        ... ).images\n\n        >>> images[0].save(\"robot_cat.png\")\n        ```\n"



def SCREAMING_SNAKE_CASE__    (     __UpperCAmelCase ,					__UpperCAmelCase ,					__UpperCAmelCase=8				)						->						Dict:
   lowercase__:     List[Any]      =   height // scale_factor**2
   if height % scale_factor**2 != 0:
      new_height += 1
   lowercase__:     str      =   width // scale_factor**2
   if width % scale_factor**2 != 0:
      new_width += 1
   return new_height * scale_factor, new_width * scale_factor



def SCREAMING_SNAKE_CASE__    (     __UpperCAmelCase ,					__UpperCAmelCase=5_1_2 ,					__UpperCAmelCase=5_1_2				)						->						List[Any]:
   lowercase__:     Tuple      =   pil_image.resize((w, h) ,					resample=Image.BICUBIC ,					reducing_gap=1				)
   lowercase__:     List[Any]      =   np.array(pil_image.convert('''RGB'''				)				)
   lowercase__:     List[str]      =   arr.astype(np.floataa				) / 1_2_7.5 - 1
   lowercase__:     Optional[int]      =   np.transpose(__UpperCAmelCase ,					[2, 0, 1]				)
   lowercase__:     Optional[int]      =   torch.from_numpy(__UpperCAmelCase				).unsqueeze(0				)
   return image




class 					UpperCAmelCase		(_UpperCAmelCase						):



    """simple docstring"""

    def __init__(     self					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    ):
       super().__init__()

       self.register_modules(
           unet=_UpperCAmelCase					,    scheduler=_UpperCAmelCase					,    movq=_UpperCAmelCase					,    )
       lowercase__:     Tuple      =   2 ** (len(self.movq.config.block_out_channels							) - 1)






    def _snake_case    (     self					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase							):
       # get the original timestep using init_timestep
       lowercase__:     Tuple      =   min(int(num_inference_steps * strength							)					,    _UpperCAmelCase							)

       lowercase__:     Any      =   max(num_inference_steps - init_timestep					,    0							)
       lowercase__:     Optional[Any]      =   self.scheduler.timesteps[t_start:]

       return timesteps, num_inference_steps - t_start






    def _snake_case    (     self					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase=None							):
       if not isinstance(_UpperCAmelCase					,    (torch.Tensor, PIL.Image.Image, list)							):
          raise ValueError(
              F"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_UpperCAmelCase							)}"""							)

       lowercase__:     Optional[Any]      =   image.to(device=_UpperCAmelCase					,    dtype=_UpperCAmelCase							)

       lowercase__:     Optional[Any]      =   batch_size * num_images_per_prompt

       if image.shape[1] == 4:
          lowercase__:     Dict      =   image

       else:
          if isinstance(_UpperCAmelCase					,    _UpperCAmelCase							) and len(_UpperCAmelCase							) != batch_size:
             raise ValueError(
                 F"""You have passed a list of generators of length {len(_UpperCAmelCase							)}, but requested an effective batch"""
                 F""" size of {batch_size}. Make sure the batch size matches the length of the generators."""							)

          elif isinstance(_UpperCAmelCase					,    _UpperCAmelCase							):
             lowercase__:     Dict      =   [
                 self.movq.encode(image[i : i + 1]							).latent_dist.sample(generator[i]							) for i in range(_UpperCAmelCase							)
             ]
             lowercase__:     Optional[Any]      =   torch.cat(_UpperCAmelCase					,    dim=0							)
          else:
             lowercase__:     Union[str, Any]      =   self.movq.encode(_UpperCAmelCase							).latent_dist.sample(_UpperCAmelCase							)

          lowercase__:     Optional[Any]      =   self.movq.config.scaling_factor * init_latents

       lowercase__:     Any      =   torch.cat([init_latents]					,    dim=0							)

       lowercase__:     List[Any]      =   init_latents.shape
       lowercase__:     Optional[int]      =   randn_tensor(_UpperCAmelCase					,    generator=_UpperCAmelCase					,    device=_UpperCAmelCase					,    dtype=_UpperCAmelCase							)

       # get latents
       lowercase__:     Tuple      =   self.scheduler.add_noise(_UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase							)

       lowercase__:     str      =   init_latents

       return latents






    def _snake_case    (     self					,    _UpperCAmelCase=0							):
       if is_accelerate_available():
          from accelerate import cpu_offload
       else:
          raise ImportError('''Please install accelerate via `pip install accelerate`'''							)

       lowercase__:     Union[str, Any]      =   torch.device(F"""cuda:{gpu_id}"""							)

       lowercase__:     int      =   [
           self.unet,
           self.movq,
       ]
       for cpu_offloaded_model in models:
          if cpu_offloaded_model is not None:
             cpu_offload(_UpperCAmelCase					,    _UpperCAmelCase							)






    def _snake_case    (     self					,    _UpperCAmelCase=0							):
       if is_accelerate_available() and is_accelerate_version('''>='''					,    '''0.17.0.dev0'''							):
          from accelerate import cpu_offload_with_hook
       else:
          raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'''							)

       lowercase__:     List[str]      =   torch.device(F"""cuda:{gpu_id}"""							)

       if self.device.type != "cpu":
          self.to('''cpu'''					,    silence_dtype_warnings=_UpperCAmelCase							)
          torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

       lowercase__:     Tuple      =   None
       for cpu_offloaded_model in [self.unet, self.movq]:
          lowercase__,				lowercase__:     List[Any]      =   cpu_offload_with_hook(_UpperCAmelCase					,    _UpperCAmelCase					,    prev_module_hook=_UpperCAmelCase							)

       # We'll offload the last model manually.
       lowercase__:     List[str]      =   hook






    @property
    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
    def _snake_case    (     self							):
       if not hasattr(self.unet					,    '''_hf_hook'''							):
          return self.device
       for module in self.unet.modules():
          if (
              hasattr(_UpperCAmelCase					,    '''_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()
    @replace_example_docstring(_UpperCAmelCase							)
    def __call__(     self					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase = 512					,    _UpperCAmelCase = 512					,    _UpperCAmelCase = 100					,    _UpperCAmelCase = 4.0					,    _UpperCAmelCase = 0.3					,    _UpperCAmelCase = 1					,    _UpperCAmelCase = None					,    _UpperCAmelCase = "pil"					,    _UpperCAmelCase = True					,    ):
       lowercase__:     str      =   self._execution_device

       lowercase__:     Optional[int]      =   guidance_scale > 1.0

       if isinstance(_UpperCAmelCase					,    _UpperCAmelCase							):
          lowercase__:     List[Any]      =   torch.cat(_UpperCAmelCase					,    dim=0							)
       if isinstance(_UpperCAmelCase					,    _UpperCAmelCase							):
          lowercase__:     Optional[int]      =   torch.cat(_UpperCAmelCase					,    dim=0							)
       if isinstance(_UpperCAmelCase					,    _UpperCAmelCase							):
          lowercase__:     Any      =   torch.cat(_UpperCAmelCase					,    dim=0							)

       lowercase__:     Optional[Any]      =   image_embeds.shape[0]

       if do_classifier_free_guidance:
          lowercase__:     str      =   image_embeds.repeat_interleave(_UpperCAmelCase					,    dim=0							)
          lowercase__:     Tuple      =   negative_image_embeds.repeat_interleave(_UpperCAmelCase					,    dim=0							)
          lowercase__:     Dict      =   hint.repeat_interleave(_UpperCAmelCase					,    dim=0							)

       lowercase__:     Optional[int]      =   torch.cat([negative_image_embeds, image_embeds]					,    dim=0							).to(dtype=self.unet.dtype					,    device=_UpperCAmelCase							)
       lowercase__:     Tuple      =   torch.cat([hint, hint]					,    dim=0							).to(dtype=self.unet.dtype					,    device=_UpperCAmelCase							)

       if not isinstance(_UpperCAmelCase					,    _UpperCAmelCase							):
          lowercase__:     int      =   [image]
       if not all(isinstance(_UpperCAmelCase					,    (PIL.Image.Image, torch.Tensor)							) for i in image							):
          raise ValueError(
              F"""Input is in incorrect format: {[type(_UpperCAmelCase							) for i in image]}. Currently, we only support  PIL image and pytorch tensor"""							)

       lowercase__:     int      =   torch.cat([prepare_image(_UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase							) for i in image]					,    dim=0							)
       lowercase__:     Optional[Any]      =   image.to(dtype=image_embeds.dtype					,    device=_UpperCAmelCase							)

       lowercase__:     Optional[Any]      =   self.movq.encode(_UpperCAmelCase							)['''latents''']
       lowercase__:     int      =   latents.repeat_interleave(_UpperCAmelCase					,    dim=0							)
       self.scheduler.set_timesteps(_UpperCAmelCase					,    device=_UpperCAmelCase							)
       lowercase__,				lowercase__:     Any      =   self.get_timesteps(_UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase							)
       lowercase__:     str      =   timesteps[:1].repeat(batch_size * num_images_per_prompt							)
       lowercase__,				lowercase__:     List[Any]      =   downscale_height_and_width(_UpperCAmelCase					,    _UpperCAmelCase					,    self.movq_scale_factor							)
       lowercase__:     List[Any]      =   self.prepare_latents(
           _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    image_embeds.dtype					,    _UpperCAmelCase					,    _UpperCAmelCase							)
       for i, t in enumerate(self.progress_bar(_UpperCAmelCase							)							):
          # expand the latents if we are doing classifier free guidance
          lowercase__:     Dict      =   torch.cat([latents] * 2							) if do_classifier_free_guidance else latents

          lowercase__:     List[Any]      =   {'''image_embeds''': image_embeds, '''hint''': hint}
          lowercase__:     List[Any]      =   self.unet(
              sample=_UpperCAmelCase					,    timestep=_UpperCAmelCase					,    encoder_hidden_states=_UpperCAmelCase					,    added_cond_kwargs=_UpperCAmelCase					,    return_dict=_UpperCAmelCase					,    )[0]

          if do_classifier_free_guidance:
             lowercase__,				lowercase__:     Any      =   noise_pred.split(latents.shape[1]					,    dim=1							)
             lowercase__,				lowercase__:     List[str]      =   noise_pred.chunk(2							)
             lowercase__,				lowercase__:     Tuple      =   variance_pred.chunk(2							)
             lowercase__:     Union[str, Any]      =   noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
             lowercase__:     int      =   torch.cat([noise_pred, variance_pred_text]					,    dim=1							)

          if not (
              hasattr(self.scheduler.config					,    '''variance_type'''							)
              and self.scheduler.config.variance_type in ["learned", "learned_range"]
          ):
             lowercase__,				lowercase__:     List[str]      =   noise_pred.split(latents.shape[1]					,    dim=1							)

          # compute the previous noisy sample x_t -> x_t-1

          lowercase__:     List[Any]      =   self.scheduler.step(
              _UpperCAmelCase					,    _UpperCAmelCase					,    _UpperCAmelCase					,    generator=_UpperCAmelCase					,    )[0]

       # post-processing
       lowercase__:     Tuple      =   self.movq.decode(_UpperCAmelCase					,    force_not_quantize=_UpperCAmelCase							)['''sample''']

       if output_type not in ["pt", "np", "pil"]:
          raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}"""							)

       if output_type in ["np", "pil"]:
          lowercase__:     Dict      =   image * 0.5 + 0.5
          lowercase__:     int      =   image.clamp(0					,    1							)
          lowercase__:     Optional[Any]      =   image.cpu().permute(0					,    2					,    3					,    1							).float().numpy()

       if output_type == "pil":
          lowercase__:     str      =   self.numpy_to_pil(_UpperCAmelCase							)

       if not return_dict:
          return (image,)

       return ImagePipelineOutput(images=_UpperCAmelCase							)

"""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'''],
           )					,    )
