

import inspect
import unittest

from transformers import DataaVecVisionConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch
      from torch import nn

      from transformers import (
          MODEL_MAPPING,
          DataaVecVisionForImageClassification,
          DataaVecVisionForSemanticSegmentation,
          DataaVecVisionModel,
      )
      from transformers.models.dataavec.modeling_dataavec_vision import DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import BeitImageProcessor






class     __magic_name__     :


 def __init__(    self		:			List[str]      ,    lowerCAmelCase__		:			Tuple      ,    lowerCAmelCase__		:			Union[str, Any]=1_0_0      ,    lowerCAmelCase__		:			int=1_3      ,    lowerCAmelCase__		:			Union[str, Any]=3_0      ,    lowerCAmelCase__		:			List[Any]=2      ,    lowerCAmelCase__		:			Optional[Any]=3      ,    lowerCAmelCase__		:			Optional[int]=True      ,    lowerCAmelCase__		:			Dict=True      ,    lowerCAmelCase__		:			List[Any]=3_2      ,    lowerCAmelCase__		:			Optional[Any]=4      ,    lowerCAmelCase__		:			str=4      ,    lowerCAmelCase__		:			List[str]=3_7      ,    lowerCAmelCase__		:			List[str]="gelu"      ,    lowerCAmelCase__		:			List[Any]=0.1      ,    lowerCAmelCase__		:			Optional[int]=0.1      ,    lowerCAmelCase__		:			List[str]=1_0      ,    lowerCAmelCase__		:			Dict=0.02      ,    lowerCAmelCase__		:			List[Any]=3      ,    lowerCAmelCase__		:			List[str]=None      ,    lowerCAmelCase__		:			List[str]=[0, 1, 2, 3]      ,    )     ->   List[str]:
   UpperCAmelCase          =	parent
   UpperCAmelCase          =	1_0_0
   UpperCAmelCase          =	batch_size
   UpperCAmelCase          =	image_size
   UpperCAmelCase          =	patch_size
   UpperCAmelCase          =	num_channels
   UpperCAmelCase          =	is_training
   UpperCAmelCase          =	use_labels
   UpperCAmelCase          =	hidden_size
   UpperCAmelCase          =	num_hidden_layers
   UpperCAmelCase          =	num_attention_heads
   UpperCAmelCase          =	intermediate_size
   UpperCAmelCase          =	hidden_act
   UpperCAmelCase          =	hidden_dropout_prob
   UpperCAmelCase          =	attention_probs_dropout_prob
   UpperCAmelCase          =	type_sequence_label_size
   UpperCAmelCase          =	initializer_range
   UpperCAmelCase          =	scope
   UpperCAmelCase          =	out_indices
   UpperCAmelCase          =	num_labels

   # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
   UpperCAmelCase          =	(image_size // patch_size) ** 2
   UpperCAmelCase          =	num_patches + 1


 def _UpperCamelCase						(    self		:			Union[str, Any]     )     ->   int:
   UpperCAmelCase          =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

   UpperCAmelCase          =	None
   UpperCAmelCase          =	None
   if self.use_labels:
     UpperCAmelCase          =	ids_tensor([self.batch_size]      ,    self.type_sequence_label_size     )
     UpperCAmelCase          =	ids_tensor([self.batch_size, self.image_size, self.image_size]      ,    self.num_labels     )

   UpperCAmelCase          =	self.get_config()

   return config, pixel_values, labels, pixel_labels


 def _UpperCamelCase						(    self		:			Any     )     ->   str:
   return DataaVecVisionConfig(
       vocab_size=self.vocab_size      ,    image_size=self.image_size      ,    patch_size=self.patch_size      ,    num_channels=self.num_channels      ,    hidden_size=self.hidden_size      ,    num_hidden_layers=self.num_hidden_layers      ,    num_attention_heads=self.num_attention_heads      ,    intermediate_size=self.intermediate_size      ,    hidden_act=self.hidden_act      ,    hidden_dropout_prob=self.hidden_dropout_prob      ,    attention_probs_dropout_prob=self.attention_probs_dropout_prob      ,    is_decoder=lowerCAmelCase__      ,    initializer_range=self.initializer_range      ,    out_indices=self.out_indices      ,    )


 def _UpperCamelCase						(    self		:			int      ,    lowerCAmelCase__		:			Optional[int]      ,    lowerCAmelCase__		:			Dict      ,    lowerCAmelCase__		:			str      ,    lowerCAmelCase__		:			str     )     ->   Any:
   UpperCAmelCase          =	DataaVecVisionModel(config=lowerCAmelCase__     )
   model.to(lowerCAmelCase__     )
   model.eval()
   UpperCAmelCase          =	model(lowerCAmelCase__     )
   # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
   UpperCAmelCase          =	(self.image_size // self.patch_size) ** 2
   self.parent.assertEqual(result.last_hidden_state.shape      ,    (self.batch_size, num_patches + 1, self.hidden_size)     )


 def _UpperCamelCase						(    self		:			Dict      ,    lowerCAmelCase__		:			str      ,    lowerCAmelCase__		:			List[Any]      ,    lowerCAmelCase__		:			int      ,    lowerCAmelCase__		:			Tuple     )     ->   Union[str, Any]:
   UpperCAmelCase          =	self.type_sequence_label_size
   UpperCAmelCase          =	DataaVecVisionForImageClassification(lowerCAmelCase__     )
   model.to(lowerCAmelCase__     )
   model.eval()
   UpperCAmelCase          =	model(lowerCAmelCase__      ,    labels=lowerCAmelCase__     )
   self.parent.assertEqual(result.logits.shape      ,    (self.batch_size, self.type_sequence_label_size)     )


 def _UpperCamelCase						(    self		:			Optional[Any]      ,    lowerCAmelCase__		:			Union[str, Any]      ,    lowerCAmelCase__		:			Union[str, Any]      ,    lowerCAmelCase__		:			Any      ,    lowerCAmelCase__		:			int     )     ->   Any:
   UpperCAmelCase          =	self.num_labels
   UpperCAmelCase          =	DataaVecVisionForSemanticSegmentation(lowerCAmelCase__     )
   model.to(lowerCAmelCase__     )
   model.eval()
   UpperCAmelCase          =	model(lowerCAmelCase__     )
   self.parent.assertEqual(
       result.logits.shape      ,    (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)     )
   UpperCAmelCase          =	model(lowerCAmelCase__      ,    labels=lowerCAmelCase__     )
   self.parent.assertEqual(
       result.logits.shape      ,    (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)     )


 def _UpperCamelCase						(    self		:			Optional[int]     )     ->   Dict:
   UpperCAmelCase          =	self.prepare_config_and_inputs()
   UpperCAmelCase   ,						UpperCAmelCase   ,						UpperCAmelCase   ,						UpperCAmelCase          =	config_and_inputs
   UpperCAmelCase          =	{"pixel_values": pixel_values}
   return config, inputs_dict






@require_torch
class     __magic_name__     (							_snake_case						,    _snake_case						,    unittest.TestCase     ):
 UpperCAmelCase				     =    (
     (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
     if is_torch_available()
     else ()
 )
 UpperCAmelCase				     =    (
     {
         """feature-extraction""": DataaVecVisionModel,
         """image-classification""": DataaVecVisionForImageClassification,
         """image-segmentation""": DataaVecVisionForSemanticSegmentation,
     }
     if is_torch_available()
     else {}
 )

 UpperCAmelCase				     =    False
 UpperCAmelCase				     =    False
 UpperCAmelCase				     =    False


 def _UpperCamelCase						(    self		:			List[str]     )     ->   Optional[Any]:
   UpperCAmelCase          =	DataaVecVisionModelTester(self     )
   UpperCAmelCase          =	ConfigTester(
       self      ,    config_class=lowerCAmelCase__      ,    has_text_modality=lowerCAmelCase__      ,    hidden_size=3_7     )


 def _UpperCamelCase						(    self		:			Union[str, Any]     )     ->   List[str]:
   self.config_tester.run_common_tests()


 def _UpperCamelCase						(    self		:			str     )     ->   Dict:
   # Data2VecVision does not use inputs_embeds
   pass


 @require_torch_multi_gpu
 @unittest.skip(
     reason="Data2VecVision has some layers using `add_module` which doesn't work well with `nn.DataParallel`"     )
 def _UpperCamelCase						(    self		:			Optional[int]     )     ->   Optional[Any]:
   pass


 def _UpperCamelCase						(    self		:			Dict     )     ->   Optional[Any]:
   UpperCAmelCase   ,						UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     UpperCAmelCase          =	model_class(lowerCAmelCase__     )
     self.assertIsInstance(model.get_input_embeddings()      ,    (nn.Module)     )
     UpperCAmelCase          =	model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(lowerCAmelCase__      ,    nn.Linear     )     )


 def _UpperCamelCase						(    self		:			Optional[Any]     )     ->   int:
   UpperCAmelCase   ,						UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     UpperCAmelCase          =	model_class(lowerCAmelCase__     )
     UpperCAmelCase          =	inspect.signature(model.forward     )
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     UpperCAmelCase          =	[*signature.parameters.keys()]

     UpperCAmelCase          =	["pixel_values"]
     self.assertListEqual(arg_names[:1]      ,    lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Union[str, Any]     )     ->   Tuple:
   UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			List[Any]     )     ->   Dict:
   UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_segmentation(*lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Any     )     ->   str:
   if not self.model_tester.is_training:
     return

   UpperCAmelCase   ,						UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase          =	True

   for model_class in self.all_model_classes:
     if model_class in [*get_values(lowerCAmelCase__     )]:
       continue

     UpperCAmelCase          =	model_class(lowerCAmelCase__     )
     model.to(lowerCAmelCase__     )
     model.train()
     UpperCAmelCase          =	self._prepare_for_class(lowerCAmelCase__      ,    lowerCAmelCase__      ,    return_labels=lowerCAmelCase__     )
     UpperCAmelCase          =	model(**lowerCAmelCase__     ).loss
     loss.backward()


 def _UpperCamelCase						(    self		:			str     )     ->   str:
   UpperCAmelCase   ,						UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs_for_common()
   if not self.model_tester.is_training:
     return

   UpperCAmelCase          =	False
   UpperCAmelCase          =	True

   for model_class in self.all_model_classes:
     if model_class in [*get_values(lowerCAmelCase__     )] or not model_class.supports_gradient_checkpointing:
       continue
     # TODO: remove the following 3 lines once we have a MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
     # this can then be incorporated into _prepare_for_class in test_modeling_common.py
     elif model_class.__name__ == "Data2VecVisionForSemanticSegmentation":
       UpperCAmelCase   ,						UpperCAmelCase   ,						UpperCAmelCase   ,						UpperCAmelCase          =	inputs_dict["pixel_values"].shape
       UpperCAmelCase          =	torch.zeros(
           [self.model_tester.batch_size, height, width]      ,    device=lowerCAmelCase__     ).long()
     UpperCAmelCase          =	model_class(lowerCAmelCase__     )
     model.gradient_checkpointing_enable()
     model.to(lowerCAmelCase__     )
     model.train()
     UpperCAmelCase          =	self._prepare_for_class(lowerCAmelCase__      ,    lowerCAmelCase__      ,    return_labels=lowerCAmelCase__     )
     UpperCAmelCase          =	model(**lowerCAmelCase__     ).loss
     loss.backward()


 def _UpperCamelCase						(    self		:			Tuple     )     ->   Optional[int]:
   UpperCAmelCase   ,						UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs_for_common()

   UpperCAmelCase          =	_config_zero_init(lowerCAmelCase__     )
   for model_class in self.all_model_classes:
     UpperCAmelCase          =	model_class(config=lowerCAmelCase__     )
     for name, param in model.named_parameters():
       # we skip lambda parameters as these require special initial values
       # determined by config.layer_scale_init_value
       if "lambda" in name:
         continue
       if param.requires_grad:
         self.assertIn(
             ((param.data.mean() * 1e9).round() / 1e9).item()      ,    [0.0, 1.0]      ,    msg=f"Parameter {name} of model {model_class} seems not properly initialized"      ,    )


 def _UpperCamelCase						(    self		:			Any      ,    lowerCAmelCase__		:			List[str]      ,    lowerCAmelCase__		:			str      ,    lowerCAmelCase__		:			str      ,    lowerCAmelCase__		:			Optional[Any]=2e-4      ,    lowerCAmelCase__		:			List[str]="outputs"      ,    lowerCAmelCase__		:			str=None     )     ->   int:
   # We override with a slightly higher tol value, as semseg models tend to diverge a bit more
   super().check_pt_tf_outputs(lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__      ,    lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Dict     )     ->   Dict:
   UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__     )


 @slow
 def _UpperCamelCase						(    self		:			int     )     ->   Optional[int]:
   for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     UpperCAmelCase          =	DataaVecVisionModel.from_pretrained(lowerCAmelCase__     )
     self.assertIsNotNone(lowerCAmelCase__     )

def   _lowerCAmelCase(						):
  UpperCAmelCase          =	Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"      )
  return image






@require_torch
@require_vision
class     __magic_name__     (							unittest.TestCase     ):


 @cached_property
 def _UpperCamelCase						(    self		:			Optional[int]     )     ->   Union[str, Any]:
   return (
       BeitImageProcessor.from_pretrained("facebook/data2vec-vision-base-ft1k"     ) if is_vision_available() else None
   )


 @slow
 def _UpperCamelCase						(    self		:			List[str]     )     ->   Any:
   UpperCAmelCase          =	DataaVecVisionForImageClassification.from_pretrained("facebook/data2vec-vision-base-ft1k"     ).to(
       lowerCAmelCase__     )

   UpperCAmelCase          =	self.default_image_processor
   UpperCAmelCase          =	prepare_img()
   UpperCAmelCase          =	image_processor(images=lowerCAmelCase__      ,    return_tensors="pt"     ).to(lowerCAmelCase__     )

   # forward pass
   with torch.no_grad():
     UpperCAmelCase          =	model(**lowerCAmelCase__     )
   UpperCAmelCase          =	outputs.logits

   # verify the logits
   UpperCAmelCase          =	torch.Size((1, 1_0_0_0)     )
   self.assertEqual(logits.shape      ,    lowerCAmelCase__     )

   UpperCAmelCase          =	torch.tensor([0.3_277, -0.1_395, 0.0_911]     ).to(lowerCAmelCase__     )

   self.assertTrue(torch.allclose(logits[0, :3]      ,    lowerCAmelCase__      ,    atol=1e-4     )     )

   UpperCAmelCase          =	[model.config.labelaid[i] for i in ["remote control, remote", "tabby, tabby cat"]]
   self.assertEqual(logits[0].topk(2     ).indices.cpu().tolist()      ,    lowerCAmelCase__     )






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__							=			logging.get_logger(__name__)


if is_vision_available():
      import PIL






class     __magic_name__     (							_snake_case     ):
 UpperCAmelCase				     =    ["""pixel_values"""]


 def __init__(    self		:			str      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Dict[str, int] = None      ,    lowerCAmelCase__		:			PILImageResampling = PILImageResampling.BICUBIC      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Dict[str, int] = None      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Union[int, float] = 1 / 2_5_5      ,    lowerCAmelCase__		:			bool = True      ,    lowerCAmelCase__		:			Optional[Union[float, List[float]]] = None      ,    lowerCAmelCase__		:			Optional[Union[float, List[float]]] = None      ,    lowerCAmelCase__		:			bool = True      ,    **lowerCAmelCase__		:			str      ,    )     ->   None:
   super().__init__(**lowerCAmelCase__     )
   UpperCAmelCase          =	size if size is not None else {"shortest_edge": 2_2_4}
   UpperCAmelCase          =	get_size_dict(lowerCAmelCase__      ,    default_to_square=lowerCAmelCase__     )
   UpperCAmelCase          =	crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
   UpperCAmelCase          =	get_size_dict(lowerCAmelCase__     )

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


 def _UpperCamelCase						(    self		:			Optional[Any]      ,    lowerCAmelCase__		:			np.ndarray      ,    lowerCAmelCase__		:			Dict[str, int]      ,    lowerCAmelCase__		:			PILImageResampling = PILImageResampling.BICUBIC      ,    lowerCAmelCase__		:			Optional[Union[str, ChannelDimension]] = None      ,    **lowerCAmelCase__		:			Optional[int]      ,    )     ->   np.ndarray:
   UpperCAmelCase          =	get_size_dict(lowerCAmelCase__      ,    default_to_square=lowerCAmelCase__     )
   UpperCAmelCase          =	get_resize_output_image_size(
       lowerCAmelCase__      ,    size=(size["height"], size["width"])      ,    default_to_square=lowerCAmelCase__     )
   return resize(lowerCAmelCase__      ,    size=lowerCAmelCase__      ,    resample=lowerCAmelCase__      ,    data_format=lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			List[Any]      ,    lowerCAmelCase__		:			np.ndarray      ,    lowerCAmelCase__		:			Dict[str, int]      ,    lowerCAmelCase__		:			Optional[Union[str, ChannelDimension]] = None      ,    **lowerCAmelCase__		:			List[Any]      ,    )     ->   np.ndarray:
   UpperCAmelCase          =	get_size_dict(lowerCAmelCase__     )
   return center_crop(lowerCAmelCase__      ,    size=(size["height"], size["width"])      ,    data_format=lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Any      ,    lowerCAmelCase__		:			np.ndarray      ,    lowerCAmelCase__		:			Union[int, float]      ,    lowerCAmelCase__		:			Optional[Union[str, ChannelDimension]] = None      ,    **lowerCAmelCase__		:			List[Any]      ,    )     ->   Optional[int]:
   return rescale(lowerCAmelCase__      ,    scale=lowerCAmelCase__      ,    data_format=lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			Union[str, Any]      ,    lowerCAmelCase__		:			np.ndarray      ,    lowerCAmelCase__		:			Union[float, List[float]]      ,    lowerCAmelCase__		:			Union[float, List[float]]      ,    lowerCAmelCase__		:			Optional[Union[str, ChannelDimension]] = None      ,    **lowerCAmelCase__		:			List[str]      ,    )     ->   np.ndarray:
   return normalize(lowerCAmelCase__      ,    mean=lowerCAmelCase__      ,    std=lowerCAmelCase__      ,    data_format=lowerCAmelCase__      ,    **lowerCAmelCase__     )


 def _UpperCamelCase						(    self		:			List[str]      ,    lowerCAmelCase__		:			ImageInput      ,    lowerCAmelCase__		:			bool = None      ,    lowerCAmelCase__		:			Dict[str, int] = None      ,    lowerCAmelCase__		:			PILImageResampling = None      ,    lowerCAmelCase__		:			bool = None      ,    lowerCAmelCase__		:			int = None      ,    lowerCAmelCase__		:			bool = None      ,    lowerCAmelCase__		:			float = None      ,    lowerCAmelCase__		:			bool = None      ,    lowerCAmelCase__		:			Optional[Union[float, List[float]]] = None      ,    lowerCAmelCase__		:			Optional[Union[float, List[float]]] = None      ,    lowerCAmelCase__		:			bool = None      ,    lowerCAmelCase__		:			Optional[Union[str, TensorType]] = None      ,    lowerCAmelCase__		:			Optional[ChannelDimension] = ChannelDimension.FIRST      ,    **lowerCAmelCase__		:			int      ,    )     ->   PIL.Image.Image:
   UpperCAmelCase          =	do_resize if do_resize is not None else self.do_resize
   UpperCAmelCase          =	size if size is not None else self.size
   UpperCAmelCase          =	get_size_dict(lowerCAmelCase__      ,    default_to_square=lowerCAmelCase__     )
   UpperCAmelCase          =	resample if resample is not None else self.resample
   UpperCAmelCase          =	do_center_crop if do_center_crop is not None else self.do_center_crop
   UpperCAmelCase          =	crop_size if crop_size is not None else self.crop_size
   UpperCAmelCase          =	get_size_dict(lowerCAmelCase__     )
   UpperCAmelCase          =	do_rescale if do_rescale is not None else self.do_rescale
   UpperCAmelCase          =	rescale_factor if rescale_factor is not None else self.rescale_factor
   UpperCAmelCase          =	do_normalize if do_normalize is not None else self.do_normalize
   UpperCAmelCase          =	image_mean if image_mean is not None else self.image_mean
   UpperCAmelCase          =	image_std if image_std is not None else self.image_std
   UpperCAmelCase          =	do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

   UpperCAmelCase          =	make_list_of_images(lowerCAmelCase__     )

   if not valid_images(lowerCAmelCase__     ):
     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:
     UpperCAmelCase          =	[convert_to_rgb(lowerCAmelCase__     ) for image in images]

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

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

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

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

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

   UpperCAmelCase          =	[to_channel_dimension_format(lowerCAmelCase__      ,    lowerCAmelCase__     ) for image in images]

   UpperCAmelCase          =	{"pixel_values": images}
   return BatchFeature(data=lowerCAmelCase__      ,    tensor_type=lowerCAmelCase__     )



