



'''simple docstring'''


import gc
import random
import tempfile
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class  SCREAMING_SNAKE_CASE (  _a   ,						_a   ,						unittest.TestCase		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  StableDiffusionDiffEditPipeline
    _SCREAMING_SNAKE_CASE	  =  TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""height""", """width""", """image"""} | {"""image_latents"""}
    _SCREAMING_SNAKE_CASE	  =  TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"""image"""} | {"""image_latents"""}
    _SCREAMING_SNAKE_CASE	  =  frozenset(
        []		)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
    _SCREAMING_SNAKE_CASE	  =  frozenset([]		)






    def  A       (  self      :					Dict ):


       """simple docstring"""







       torch.manual_seed(0 )
       UpperCamelCase					=  UNetaDConditionModel(
           block_out_channels=(3_2, 6_4)  ,						layers_per_block=2  ,						sample_size=3_2  ,						in_channels=4  ,						out_channels=4  ,						down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')  ,						up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')  ,						cross_attention_dim=3_2  ,						attention_head_dim=(2, 4)  ,						use_linear_projection=UpperCamelCase__  ,						)
       UpperCamelCase					=  DDIMScheduler(
           beta_start=0.0_0_0_8_5  ,						beta_end=0.0_1_2  ,						beta_schedule='scaled_linear'  ,						clip_sample=UpperCamelCase__  ,						set_alpha_to_one=UpperCamelCase__  ,						)
       UpperCamelCase					=  DDIMInverseScheduler(
           beta_start=0.0_0_0_8_5  ,						beta_end=0.0_1_2  ,						beta_schedule='scaled_linear'  ,						clip_sample=UpperCamelCase__  ,						set_alpha_to_zero=UpperCamelCase__  ,						)
       torch.manual_seed(0 )
       UpperCamelCase					=  AutoencoderKL(
           block_out_channels=[3_2, 6_4]  ,						in_channels=3  ,						out_channels=3  ,						down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']  ,						up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']  ,						latent_channels=4  ,						sample_size=1_2_8  ,						)
       torch.manual_seed(0 )
       UpperCamelCase					=  CLIPTextConfig(
           bos_token_id=0  ,						eos_token_id=2  ,						hidden_size=3_2  ,						intermediate_size=3_7  ,						layer_norm_eps=1E-0_5  ,						num_attention_heads=4  ,						num_hidden_layers=5  ,						pad_token_id=1  ,						vocab_size=1_0_0_0  ,						hidden_act='gelu'  ,						projection_dim=5_1_2  ,						)
       UpperCamelCase					=  CLIPTextModel(UpperCamelCase__ )
       UpperCamelCase					=  CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' )

       UpperCamelCase					=  {
           'unet': unet,
           'scheduler': scheduler,
           'inverse_scheduler': inverse_scheduler,
           'vae': vae,
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'safety_checker': None,
           'feature_extractor': None,
       }

       return components






    def  A       (  self      :					Any  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					List[Any]=0 ):


       """simple docstring"""







       UpperCamelCase					=  floats_tensor((1, 1_6, 1_6)  ,						rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ )
       UpperCamelCase					=  floats_tensor((1, 2, 4, 1_6, 1_6)  ,						rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ )
       if str(UpperCamelCase__ ).startswith('mps' ):
          UpperCamelCase					=  torch.manual_seed(UpperCamelCase__ )
       else:
          UpperCamelCase					=  torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ )
       UpperCamelCase					=  {
           'prompt': 'a dog and a newt',
           'mask_image': mask,
           'image_latents': latents,
           'generator': generator,
           'num_inference_steps': 2,
           'inpaint_strength': 1.0,
           'guidance_scale': 6.0,
           'output_type': 'numpy',
       }

       return inputs






    def  A       (  self      :					Union[str, Any]  ,						UpperCamelCase__      :					List[Any]  ,						UpperCamelCase__      :					Union[str, Any]=0 ):


       """simple docstring"""







       UpperCamelCase					=  floats_tensor((1, 3, 3_2, 3_2)  ,						rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ )
       UpperCamelCase					=  image.cpu().permute(0  ,						2  ,						3  ,						1 )[0]
       UpperCamelCase					=  Image.fromarray(np.uinta(UpperCamelCase__ ) ).convert('RGB' )
       if str(UpperCamelCase__ ).startswith('mps' ):
          UpperCamelCase					=  torch.manual_seed(UpperCamelCase__ )
       else:
          UpperCamelCase					=  torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ )
       UpperCamelCase					=  {
           'image': image,
           'source_prompt': 'a cat and a frog',
           'target_prompt': 'a dog and a newt',
           'generator': generator,
           'num_inference_steps': 2,
           'num_maps_per_mask': 2,
           'mask_encode_strength': 1.0,
           'guidance_scale': 6.0,
           'output_type': 'numpy',
       }

       return inputs






    def  A       (  self      :					Any  ,						UpperCamelCase__      :					Optional[int]  ,						UpperCamelCase__      :					List[Any]=0 ):


       """simple docstring"""







       UpperCamelCase					=  floats_tensor((1, 3, 3_2, 3_2)  ,						rng=random.Random(UpperCamelCase__ ) ).to(UpperCamelCase__ )
       UpperCamelCase					=  image.cpu().permute(0  ,						2  ,						3  ,						1 )[0]
       UpperCamelCase					=  Image.fromarray(np.uinta(UpperCamelCase__ ) ).convert('RGB' )
       if str(UpperCamelCase__ ).startswith('mps' ):
          UpperCamelCase					=  torch.manual_seed(UpperCamelCase__ )
       else:
          UpperCamelCase					=  torch.Generator(device=UpperCamelCase__ ).manual_seed(UpperCamelCase__ )
       UpperCamelCase					=  {
           'image': image,
           'prompt': 'a cat and a frog',
           'generator': generator,
           'num_inference_steps': 2,
           'inpaint_strength': 1.0,
           'guidance_scale': 6.0,
           'decode_latents': True,
           'output_type': 'numpy',
       }
       return inputs






    def  A       (  self      :					List[Any] ):


       """simple docstring"""







       if not hasattr(self.pipeline_class  ,						'_optional_components' ):
          return

       UpperCamelCase					=  self.get_dummy_components()
       UpperCamelCase					=  self.pipeline_class(**UpperCamelCase__ )
       pipe.to(UpperCamelCase__ )
       pipe.set_progress_bar_config(disable=UpperCamelCase__ )

       # set all optional components to None and update pipeline config accordingly
       for optional_component in pipe._optional_components:
          setattr(UpperCamelCase__  ,						UpperCamelCase__  ,						UpperCamelCase__ )
       pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} )

       UpperCamelCase					=  self.get_dummy_inputs(UpperCamelCase__ )
       UpperCamelCase					=  pipe(**UpperCamelCase__ )[0]

       with tempfile.TemporaryDirectory() as tmpdir:
          pipe.save_pretrained(UpperCamelCase__ )
          UpperCamelCase					=  self.pipeline_class.from_pretrained(UpperCamelCase__ )
          pipe_loaded.to(UpperCamelCase__ )
          pipe_loaded.set_progress_bar_config(disable=UpperCamelCase__ )

       for optional_component in pipe._optional_components:
          self.assertTrue(
              getattr(UpperCamelCase__  ,						UpperCamelCase__ ) is None  ,						f"""`{optional_component}` did not stay set to None after loading."""  ,						)

       UpperCamelCase					=  self.get_dummy_inputs(UpperCamelCase__ )
       UpperCamelCase					=  pipe_loaded(**UpperCamelCase__ )[0]

       UpperCamelCase					=  np.abs(output - output_loaded ).max()
       self.assertLess(UpperCamelCase__  ,						1E-4 )






    def  A       (  self      :					List[str] ):


       """simple docstring"""







       UpperCamelCase					=  'cpu'

       UpperCamelCase					=  self.get_dummy_components()
       UpperCamelCase					=  self.pipeline_class(**UpperCamelCase__ )
       pipe.to(UpperCamelCase__ )
       pipe.set_progress_bar_config(disable=UpperCamelCase__ )

       UpperCamelCase					=  self.get_dummy_mask_inputs(UpperCamelCase__ )
       UpperCamelCase					=  pipe.generate_mask(**UpperCamelCase__ )
       UpperCamelCase					=  mask[0, -3:, -3:]

       self.assertEqual(mask.shape  ,						(1, 1_6, 1_6) )
       UpperCamelCase					=  np.array([0] * 9 )
       UpperCamelCase					=  np.abs(mask_slice.flatten() - expected_slice ).max()
       self.assertLessEqual(UpperCamelCase__  ,						1E-3 )
       self.assertEqual(mask[0, -3, -4]  ,						0 )






    def  A       (  self      :					Dict ):


       """simple docstring"""







       UpperCamelCase					=  'cpu'

       UpperCamelCase					=  self.get_dummy_components()
       UpperCamelCase					=  self.pipeline_class(**UpperCamelCase__ )
       pipe.to(UpperCamelCase__ )
       pipe.set_progress_bar_config(disable=UpperCamelCase__ )

       UpperCamelCase					=  self.get_dummy_inversion_inputs(UpperCamelCase__ )
       UpperCamelCase					=  pipe.invert(**UpperCamelCase__ ).images
       UpperCamelCase					=  image[0, -1, -3:, -3:]

       self.assertEqual(image.shape  ,						(2, 3_2, 3_2, 3) )
       UpperCamelCase					=  np.array(
           [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]  ,						)
       UpperCamelCase					=  np.abs(image_slice.flatten() - expected_slice ).max()
       self.assertLessEqual(UpperCamelCase__  ,						1E-3 )






    def  A       (  self      :					List[Any] ):


       """simple docstring"""







       super().test_inference_batch_single_identical(expected_max_diff=5E-3 )






    def  A       (  self      :					Tuple ):


       """simple docstring"""







       UpperCamelCase					=  'cpu'

       UpperCamelCase					=  self.get_dummy_components()

       UpperCamelCase					=  {'beta_start': 0.0_0_0_8_5, 'beta_end': 0.0_1_2, 'beta_schedule': 'scaled_linear'}
       UpperCamelCase					=  DPMSolverMultistepScheduler(**UpperCamelCase__ )
       UpperCamelCase					=  DPMSolverMultistepInverseScheduler(**UpperCamelCase__ )

       UpperCamelCase					=  self.pipeline_class(**UpperCamelCase__ )
       pipe.to(UpperCamelCase__ )
       pipe.set_progress_bar_config(disable=UpperCamelCase__ )

       UpperCamelCase					=  self.get_dummy_inversion_inputs(UpperCamelCase__ )
       UpperCamelCase					=  pipe.invert(**UpperCamelCase__ ).images
       UpperCamelCase					=  image[0, -1, -3:, -3:]

       self.assertEqual(image.shape  ,						(2, 3_2, 3_2, 3) )
       UpperCamelCase					=  np.array(
           [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]  ,						)
       UpperCamelCase					=  np.abs(image_slice.flatten() - expected_slice ).max()
       self.assertLessEqual(UpperCamelCase__  ,						1E-3 )

@require_torch_gpu
@slow
class  SCREAMING_SNAKE_CASE (  unittest.TestCase		):






    """simple docstring"""





    def  A       (  self      :					str ):


       """simple docstring"""







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






    @classmethod
    def  A       (  cls      :					Union[str, Any] ):


       """simple docstring"""







       UpperCamelCase					=  load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png' )

       UpperCamelCase					=  raw_image.convert('RGB' ).resize((7_6_8, 7_6_8) )

       UpperCamelCase					=  raw_image






    def  A       (  self      :					Tuple ):


       """simple docstring"""







       UpperCamelCase					=  torch.manual_seed(0 )

       UpperCamelCase					=  StableDiffusionDiffEditPipeline.from_pretrained(
           'stabilityai/stable-diffusion-2-1'  ,						safety_checker=UpperCamelCase__  ,						torch_dtype=torch.floataa )
       UpperCamelCase					=  DDIMScheduler.from_config(pipe.scheduler.config )
       UpperCamelCase					=  DDIMInverseScheduler.from_config(pipe.scheduler.config )
       pipe.enable_model_cpu_offload()
       pipe.set_progress_bar_config(disable=UpperCamelCase__ )

       UpperCamelCase					=  'a bowl of fruit'
       UpperCamelCase					=  'a bowl of pears'

       UpperCamelCase					=  pipe.generate_mask(
           image=self.raw_image  ,						source_prompt=UpperCamelCase__  ,						target_prompt=UpperCamelCase__  ,						generator=UpperCamelCase__  ,						)

       UpperCamelCase					=  pipe.invert(
           prompt=UpperCamelCase__  ,						image=self.raw_image  ,						inpaint_strength=0.7  ,						generator=UpperCamelCase__ ).latents

       UpperCamelCase					=  pipe(
           prompt=UpperCamelCase__  ,						mask_image=UpperCamelCase__  ,						image_latents=UpperCamelCase__  ,						generator=UpperCamelCase__  ,						negative_prompt=UpperCamelCase__  ,						inpaint_strength=0.7  ,						output_type='numpy'  ,						).images[0]

       UpperCamelCase					=  (
           np.array(
               load_image(
                   'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
                   '/diffedit/pears.png' ).resize((7_6_8, 7_6_8) ) )
           / 2_5_5
       )
       assert np.abs((expected_image - image).max() ) < 5E-1






    def  A       (  self      :					Optional[int] ):


       """simple docstring"""







       UpperCamelCase					=  torch.manual_seed(0 )

       UpperCamelCase					=  StableDiffusionDiffEditPipeline.from_pretrained(
           'stabilityai/stable-diffusion-2-1'  ,						safety_checker=UpperCamelCase__  ,						torch_dtype=torch.floataa )
       UpperCamelCase					=  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
       UpperCamelCase					=  DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config )
       pipe.enable_model_cpu_offload()
       pipe.set_progress_bar_config(disable=UpperCamelCase__ )

       UpperCamelCase					=  'a bowl of fruit'
       UpperCamelCase					=  'a bowl of pears'

       UpperCamelCase					=  pipe.generate_mask(
           image=self.raw_image  ,						source_prompt=UpperCamelCase__  ,						target_prompt=UpperCamelCase__  ,						generator=UpperCamelCase__  ,						)

       UpperCamelCase					=  pipe.invert(
           prompt=UpperCamelCase__  ,						image=self.raw_image  ,						inpaint_strength=0.7  ,						generator=UpperCamelCase__  ,						num_inference_steps=2_5  ,						).latents

       UpperCamelCase					=  pipe(
           prompt=UpperCamelCase__  ,						mask_image=UpperCamelCase__  ,						image_latents=UpperCamelCase__  ,						generator=UpperCamelCase__  ,						negative_prompt=UpperCamelCase__  ,						inpaint_strength=0.7  ,						num_inference_steps=2_5  ,						output_type='numpy'  ,						).images[0]

       UpperCamelCase					=  (
           np.array(
               load_image(
                   'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
                   '/diffedit/pears.png' ).resize((7_6_8, 7_6_8) ) )
           / 2_5_5
       )
       assert np.abs((expected_image - image).max() ) < 5E-1







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


lowerCamelCase				:		Optional[Any]     =   logging.get_logger(__name__)


if is_vision_available():
 import PIL







class   A(						UpperCamelCase   ):



 '''simple docstring'''


 UpperCamelCase						   =						['''pixel_values''']

 def __init__(				self					:  List[Any]						,							A_					:  bool = True						,							A_					:  Dict[str, int] = None						,							A_					:  PILImageResampling = PILImageResampling.BICUBIC						,							A_					:  bool = True						,							A_					:  Dict[str, int] = None						,							A_					:  bool = True						,							A_					:  Union[int, float] = 1 / 255						,							A_					:  bool = True						,							A_					:  Optional[Union[float, List[float]]] = None						,							A_					:  Optional[Union[float, List[float]]] = None						,							A_					:  bool = True						,							**A_					:  Dict						,							)   ->	None:

       """simple docstring"""






       super().__init__(**A_  )
       lowerCamelCase_		     =    size if size is not None else {'shortest_edge': 224}
       lowerCamelCase_		     =    get_size_dict(A_						,							default_to_square=A_  )
       lowerCamelCase_		     =    crop_size if crop_size is not None else {'height': 224, 'width': 224}
       lowerCamelCase_		     =    get_size_dict(A_						,							default_to_square=A_						,							param_name='crop_size'  )

       lowerCamelCase_		     =    do_resize
       lowerCamelCase_		     =    size
       lowerCamelCase_		     =    resample
       lowerCamelCase_		     =    do_center_crop
       lowerCamelCase_		     =    crop_size
       lowerCamelCase_		     =    do_rescale
       lowerCamelCase_		     =    rescale_factor
       lowerCamelCase_		     =    do_normalize
       lowerCamelCase_		     =    image_mean if image_mean is not None else OPENAI_CLIP_MEAN
       lowerCamelCase_		     =    image_std if image_std is not None else OPENAI_CLIP_STD
       lowerCamelCase_		     =    do_convert_rgb

 def 				a__ (				self					:  Dict						,							A_					:  np.ndarray						,							A_					:  Dict[str, int]						,							A_					:  PILImageResampling = PILImageResampling.BICUBIC						,							A_					:  Optional[Union[str, ChannelDimension]] = None						,							**A_					:  Union[str, Any]						,							)   ->	np.ndarray:

       """simple docstring"""






       lowerCamelCase_		     =    get_size_dict(A_						,							default_to_square=A_  )
       if "shortest_edge" not in size:
             raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""  )
       lowerCamelCase_		     =    get_resize_output_image_size(A_						,							size=size['shortest_edge']						,							default_to_square=A_  )
       return resize(A_						,							size=A_						,							resample=A_						,							data_format=A_						,							**A_  )

 def 				a__ (				self					:  Tuple						,							A_					:  np.ndarray						,							A_					:  Dict[str, int]						,							A_					:  Optional[Union[str, ChannelDimension]] = None						,							**A_					:  Dict						,							)   ->	np.ndarray:

       """simple docstring"""






       lowerCamelCase_		     =    get_size_dict(A_  )
       if "height" not in size or "width" not in size:
             raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}"""  )
       return center_crop(A_						,							size=(size['height'], size['width'])						,							data_format=A_						,							**A_  )

 def 				a__ (				self					:  str						,							A_					:  np.ndarray						,							A_					:  Union[int, float]						,							A_					:  Optional[Union[str, ChannelDimension]] = None						,							**A_					:  Union[str, Any]						,							)   ->	str:

       """simple docstring"""






       return rescale(A_						,							scale=A_						,							data_format=A_						,							**A_  )

 def 				a__ (				self					:  Optional[Any]						,							A_					:  np.ndarray						,							A_					:  Union[float, List[float]]						,							A_					:  Union[float, List[float]]						,							A_					:  Optional[Union[str, ChannelDimension]] = None						,							**A_					:  str						,							)   ->	np.ndarray:

       """simple docstring"""






       return normalize(A_						,							mean=A_						,							std=A_						,							data_format=A_						,							**A_  )





 def 				a__ (				self					:  Any						,							A_					:  ImageInput						,							A_					:  bool = None						,							A_					:  Dict[str, int] = None						,							A_					:  PILImageResampling = None						,							A_					:  bool = None						,							A_					:  int = None						,							A_					:  bool = None						,							A_					:  float = None						,							A_					:  bool = None						,							A_					:  Optional[Union[float, List[float]]] = None						,							A_					:  Optional[Union[float, List[float]]] = None						,							A_					:  bool = None						,							A_					:  Optional[Union[str, TensorType]] = None						,							A_					:  Optional[ChannelDimension] = ChannelDimension.FIRST						,							**A_					:  Dict						,							)   ->	PIL.Image.Image:

       """simple docstring"""






       lowerCamelCase_		     =    do_resize if do_resize is not None else self.do_resize
       lowerCamelCase_		     =    size if size is not None else self.size
       lowerCamelCase_		     =    get_size_dict(A_						,							param_name='size'						,							default_to_square=A_  )
       lowerCamelCase_		     =    resample if resample is not None else self.resample
       lowerCamelCase_		     =    do_center_crop if do_center_crop is not None else self.do_center_crop
       lowerCamelCase_		     =    crop_size if crop_size is not None else self.crop_size
       lowerCamelCase_		     =    get_size_dict(A_						,							param_name='crop_size'						,							default_to_square=A_  )
       lowerCamelCase_		     =    do_rescale if do_rescale is not None else self.do_rescale
       lowerCamelCase_		     =    rescale_factor if rescale_factor is not None else self.rescale_factor
       lowerCamelCase_		     =    do_normalize if do_normalize is not None else self.do_normalize
       lowerCamelCase_		     =    image_mean if image_mean is not None else self.image_mean
       lowerCamelCase_		     =    image_std if image_std is not None else self.image_std
       lowerCamelCase_		     =    do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

       lowerCamelCase_		     =    make_list_of_images(A_  )

       if not valid_images(A_  ):
             raise ValueError(
                 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
                 'torch.Tensor, tf.Tensor or jax.ndarray.'  )

       if do_resize and size is None:
             raise ValueError('Size must be specified if do_resize is True.'  )

       if do_center_crop and crop_size is None:
             raise ValueError('Crop size must be specified if do_center_crop is True.'  )

       if do_rescale and rescale_factor is None:
             raise ValueError('Rescale factor must be specified if do_rescale is True.'  )

       if do_normalize and (image_mean is None or image_std is None):
             raise ValueError('Image mean and std must be specified if do_normalize is True.'  )

       # PIL RGBA images are converted to RGB
       if do_convert_rgb:
             lowerCamelCase_		     =    [convert_to_rgb(A_  ) for image in images]

       # All transformations expect numpy arrays.
       lowerCamelCase_		     =    [to_numpy_array(A_  ) for image in images]

       if do_resize:
             lowerCamelCase_		     =    [self.resize(image=A_						,							size=A_						,							resample=A_  ) for image in images]

       if do_center_crop:
             lowerCamelCase_		     =    [self.center_crop(image=A_						,							size=A_  ) for image in images]

       if do_rescale:
             lowerCamelCase_		     =    [self.rescale(image=A_						,							scale=A_  ) for image in images]

       if do_normalize:
             lowerCamelCase_		     =    [self.normalize(image=A_						,							mean=A_						,							std=A_  ) for image in images]

       lowerCamelCase_		     =    [to_channel_dimension_format(A_						,							A_  ) for image in images]

       lowerCamelCase_		     =    {'pixel_values': images}
       return BatchFeature(data=A_						,							tensor_type=A_  )



