





'''simple docstring'''

import inspect
import unittest
import warnings
from typing import List

from transformers import EfficientFormerConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import (
       MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
       MODEL_MAPPING,
       EfficientFormerForImageClassification,
       EfficientFormerForImageClassificationWithTeacher,
       EfficientFormerModel,
   )
   from transformers.models.efficientformer.modeling_efficientformer import (
       EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
   )


if is_vision_available():
   from PIL import Image

   from transformers import EfficientFormerImageProcessor





class lowerCamelCase    :







  def __init__(		self  ,  lowercase__  ,  lowercase__ = 13  ,  lowercase__ = 64  ,  lowercase__ = 2  ,  lowercase__ = 3  ,  lowercase__ = 3  ,  lowercase__ = True  ,  lowercase__ = True  ,  lowercase__ = 128  ,  lowercase__=[16, 32, 64, 128]  ,  lowercase__ = 7  ,  lowercase__ = 4  ,  lowercase__ = 37  ,  lowercase__ = "gelu"  ,  lowercase__ = 0.1  ,  lowercase__ = 0.1  ,  lowercase__ = 10  ,  lowercase__ = 0.02  ,  lowercase__ = 2  ,  lowercase__ = 1  ,  lowercase__ = 128  ,  lowercase__ = [2, 2, 2, 2]  ,  lowercase__ = 2  ,  lowercase__ = 2  ,  )		->    List[Any]:






        """simple docstring"""





        _snake_case		:						Tuple         =  parent
        _snake_case		:						Optional[Any]         =  batch_size
        _snake_case		:						Optional[Any]         =  image_size
        _snake_case		:						Any         =  patch_size
        _snake_case		:						Any         =  num_channels
        _snake_case		:						Any         =  is_training
        _snake_case		:						Dict         =  use_labels
        _snake_case		:						List[str]         =  hidden_size
        _snake_case		:						List[Any]         =  num_hidden_layers
        _snake_case		:						str         =  num_attention_heads
        _snake_case		:						str         =  intermediate_size
        _snake_case		:						Tuple         =  hidden_act
        _snake_case		:						Union[str, Any]         =  hidden_dropout_prob
        _snake_case		:						Union[str, Any]         =  attention_probs_dropout_prob
        _snake_case		:						Any         =  type_sequence_label_size
        _snake_case		:						Optional[int]         =  initializer_range
        _snake_case		:						Tuple         =  encoder_stride
        _snake_case		:						str         =  num_attention_outputs
        _snake_case		:						Tuple         =  embed_dim
        _snake_case		:						Tuple         =  embed_dim + 1
        _snake_case		:						List[str]         =  resolution
        _snake_case		:						Optional[int]         =  depths
        _snake_case		:						List[Any]         =  hidden_sizes
        _snake_case		:						Tuple         =  dim
        _snake_case		:						str         =  mlp_expansion_ratio







  def 					UpperCAmelCase_					(		self		)		->    List[str]:






        """simple docstring"""





        _snake_case		:						Optional[Any]         =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

        _snake_case		:						List[Any]         =  None
        if self.use_labels:
              _snake_case		:						Union[str, Any]         =  ids_tensor([self.batch_size]  ,  self.type_sequence_label_size		)

        _snake_case		:						Union[str, Any]         =  self.get_config()
        return config, pixel_values, labels







  def 					UpperCAmelCase_					(		self		)		->    Optional[int]:






        """simple docstring"""





        return EfficientFormerConfig(
            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=_A  ,  initializer_range=self.initializer_range  ,  encoder_stride=self.encoder_stride  ,  resolution=self.resolution  ,  depths=self.depths  ,  hidden_sizes=self.hidden_sizes  ,  dim=self.dim  ,  mlp_expansion_ratio=self.mlp_expansion_ratio  ,  )







  def 					UpperCAmelCase_					(		self  ,  lowercase__  ,  lowercase__  ,  lowercase__		)		->    List[str]:






        """simple docstring"""





        _snake_case		:						List[Any]         =  EfficientFormerModel(config=_A		)
        model.to(_A		)
        model.eval()
        _snake_case		:						List[Any]         =  model(_A		)
        self.parent.assertEqual(result.last_hidden_state.shape  ,  (self.batch_size, self.seq_length, self.hidden_size)		)







  def 					UpperCAmelCase_					(		self  ,  lowercase__  ,  lowercase__  ,  lowercase__		)		->    Any:






        """simple docstring"""





        _snake_case		:						Any         =  self.type_sequence_label_size
        _snake_case		:						Union[str, Any]         =  EfficientFormerForImageClassification(_A		)
        model.to(_A		)
        model.eval()
        _snake_case		:						List[str]         =  model(_A  ,  labels=_A		)
        self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.type_sequence_label_size)		)

        # test greyscale images
        _snake_case		:						Union[str, Any]         =  1
        _snake_case		:						Union[str, Any]         =  EfficientFormerForImageClassification(_A		)
        model.to(_A		)
        model.eval()

        _snake_case		:						str         =  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
        _snake_case		:						int         =  model(_A		)
        self.parent.assertEqual(result.logits.shape  ,  (self.batch_size, self.type_sequence_label_size)		)







  def 					UpperCAmelCase_					(		self		)		->    List[Any]:






        """simple docstring"""





        _snake_case		:						str         =  self.prepare_config_and_inputs()
        (
            (
            _snake_case      
        )  ,				(
            _snake_case      
        )  ,				(
            _snake_case      
        )  ,				      
        )		:						Tuple         =  config_and_inputs
        _snake_case		:						Dict         =  {'''pixel_values''': pixel_values}
        return config, inputs_dict





@require_torch
class lowerCamelCase    (lowerCAmelCase__    ,   lowerCAmelCase__    ,   unittest.TestCase       ):
  _lowercase	:						List[Any]							       =					(
      (
          EfficientFormerModel,
          EfficientFormerForImageClassificationWithTeacher,
          EfficientFormerForImageClassification,
      )
      if is_torch_available()
      else ()
  )
  _lowercase	:						Optional[Any]							       =					(
      {
          'feature-extraction': EfficientFormerModel,
          'image-classification': (
              EfficientFormerForImageClassification,
              EfficientFormerForImageClassificationWithTeacher,
          ),
      }
      if is_torch_available()
      else {}
  )
  _lowercase	:						str							       =					False

  _lowercase	:						str							       =					False
  _lowercase	:						int							       =					False
  _lowercase	:						Dict							       =					False







  def 					UpperCAmelCase_					(		self		)		->    Tuple:






        """simple docstring"""





        _snake_case		:						Optional[int]         =  EfficientFormerModelTester(self		)
        _snake_case		:						Optional[int]         =  ConfigTester(
            self  ,  config_class=_A  ,  has_text_modality=_A  ,  hidden_size=37		)







  def 					UpperCAmelCase_					(		self		)		->    str:






        """simple docstring"""





        self.config_tester.run_common_tests()







  @unittest.skip(reason='''EfficientFormer does not use inputs_embeds'''		)
  def 					UpperCAmelCase_					(		self		)		->    int:






        """simple docstring"""





        pass







  @unittest.skip(reason='''EfficientFormer does not support input and output embeddings'''		)
  def 					UpperCAmelCase_					(		self		)		->    int:






        """simple docstring"""





        pass







  def 					UpperCAmelCase_					(		self		)		->    Any:






        """simple docstring"""





        _snake_case  ,				_snake_case		:						Any         =  self.model_tester.prepare_config_and_inputs_for_common()

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

              _snake_case		:						Dict         =  ['''pixel_values''']
              self.assertListEqual(arg_names[:1]  ,  _A		)







  def 					UpperCAmelCase_					(		self		)		->    Tuple:






        """simple docstring"""





        def check_hidden_states_output(lowercase__  ,  lowercase__  ,  lowercase__		):
              _snake_case		:						Optional[Any]         =  model_class(_A		)
              model.to(_A		)
              model.eval()

              with torch.no_grad():
                    _snake_case		:						Dict         =  model(**self._prepare_for_class(_A  ,  _A		)		)

              _snake_case		:						List[Any]         =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              _snake_case		:						Any         =  getattr(
                  self.model_tester  ,  '''expected_num_hidden_layers'''  ,  self.model_tester.num_hidden_layers + 1		)
              self.assertEqual(len(_A		)  ,  _A		)

              if hasattr(self.model_tester  ,  '''encoder_seq_length'''		):
                    _snake_case		:						str         =  self.model_tester.encoder_seq_length
                    if hasattr(self.model_tester  ,  '''chunk_length'''		) and self.model_tester.chunk_length > 1:
                          _snake_case		:						Tuple         =  seq_length * self.model_tester.chunk_length
              else:
                    _snake_case		:						Dict         =  self.model_tester.seq_length

              self.assertListEqual(
                  list(hidden_states[-1].shape[-2:]		)  ,  [seq_length, self.model_tester.hidden_size]  ,  )

              if config.is_encoder_decoder:
                    _snake_case		:						Dict         =  outputs.decoder_hidden_states

                    self.assertIsInstance(_A  ,  (list, tuple)		)
                    self.assertEqual(len(_A		)  ,  _A		)
                    _snake_case		:						Union[str, Any]         =  getattr(self.model_tester  ,  '''seq_length'''  ,  _A		)
                    _snake_case		:						Dict         =  getattr(self.model_tester  ,  '''decoder_seq_length'''  ,  _A		)

                    self.assertListEqual(
                        list(hidden_states[-1].shape[-2:]		)  ,  [decoder_seq_length, self.model_tester.hidden_size]  ,  )

        _snake_case  ,				_snake_case		:						str         =  self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _snake_case		:						Optional[Any]         =  True
              check_hidden_states_output(_A  ,  _A  ,  _A		)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              _snake_case		:						List[Any]         =  True

              check_hidden_states_output(_A  ,  _A  ,  _A		)







  def 					UpperCAmelCase_					(		self  ,  lowercase__  ,  lowercase__  ,  lowercase__=False		)		->    Optional[Any]:






        """simple docstring"""





        _snake_case		:						Dict         =  super()._prepare_for_class(_A  ,  _A  ,  return_labels=_A		)

        if return_labels:
              if model_class.__name__ == "EfficientFormerForImageClassificationWithTeacher":
                    del inputs_dict["labels"]

        return inputs_dict







  def 					UpperCAmelCase_					(		self		)		->    List[str]:






        """simple docstring"""





        _snake_case		:						Union[str, Any]         =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_A		)







  @unittest.skip(reason='''EfficientFormer does not implement masked image modeling yet'''		)
  def 					UpperCAmelCase_					(		self		)		->    Optional[Any]:






        """simple docstring"""





        _snake_case		:						List[str]         =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_image_modeling(*_A		)







  def 					UpperCAmelCase_					(		self		)		->    Dict:






        """simple docstring"""





        _snake_case		:						List[str]         =  self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*_A		)







  def 					UpperCAmelCase_					(		self		)		->    Optional[Any]:






        """simple docstring"""





        if not self.model_tester.is_training:
              return

        _snake_case  ,				_snake_case		:						int         =  self.model_tester.prepare_config_and_inputs_for_common()
        _snake_case		:						List[str]         =  True

        for model_class in self.all_model_classes:
              # EfficientFormerForImageClassificationWithTeacher supports inference-only
              if (
                  model_class in get_values(_A		)
                  or model_class.__name__ == "EfficientFormerForImageClassificationWithTeacher"
              ):
                    continue
              _snake_case		:						Tuple         =  model_class(_A		)
              model.to(_A		)
              model.train()
              _snake_case		:						Any         =  self._prepare_for_class(_A  ,  _A  ,  return_labels=_A		)
              _snake_case		:						Optional[int]         =  model(**_A		).loss
              loss.backward()







  def 					UpperCAmelCase_					(		self		)		->    Union[str, Any]:






        """simple docstring"""





        _snake_case  ,				_snake_case		:						Union[str, Any]         =  self.model_tester.prepare_config_and_inputs_for_common()

        _snake_case		:						str         =  [
            {'''title''': '''multi_label_classification''', '''num_labels''': 2, '''dtype''': torch.float},
            {'''title''': '''single_label_classification''', '''num_labels''': 1, '''dtype''': torch.long},
            {'''title''': '''regression''', '''num_labels''': 1, '''dtype''': torch.float},
        ]

        for model_class in self.all_model_classes:
              if (
                  model_class
                  not in [
                      *get_values(_A		),
                  ]
                  or model_class.__name__ == "EfficientFormerForImageClassificationWithTeacher"
              ):
                    continue

              for problem_type in problem_types:
                    with self.subTest(msg=F'''Testing {model_class} with {problem_type["title"]}'''		):
                          _snake_case		:						List[str]         =  problem_type['''title''']
                          _snake_case		:						Union[str, Any]         =  problem_type['''num_labels''']

                          _snake_case		:						List[Any]         =  model_class(_A		)
                          model.to(_A		)
                          model.train()

                          _snake_case		:						Union[str, Any]         =  self._prepare_for_class(_A  ,  _A  ,  return_labels=_A		)

                          if problem_type["num_labels"] > 1:
                                _snake_case		:						List[Any]         =  inputs['''labels'''].unsqueeze(1		).repeat(1  ,  problem_type['''num_labels''']		)

                          _snake_case		:						Optional[int]         =  inputs['''labels'''].to(problem_type['''dtype''']		)

                          # This tests that we do not trigger the warning form PyTorch "Using a target size that is different
                          # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
                          # they have the same size." which is a symptom something in wrong for the regression problem.
                          # See https://github.com/huggingface/transformers/issues/11780
                          with warnings.catch_warnings(record=_A		) as warning_list:
                                _snake_case		:						Any         =  model(**_A		).loss
                          for w in warning_list:
                                if "Using a target size that is different to the input size" in str(w.message		):
                                      raise ValueError(
                                          F'''Something is going wrong in the regression problem: intercepted {w.message}'''		)

                          loss.backward()







  @slow
  def 					UpperCAmelCase_					(		self		)		->    Tuple:






        """simple docstring"""





        for model_name in EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _snake_case		:						Dict         =  EfficientFormerModel.from_pretrained(_A		)
              self.assertIsNotNone(_A		)







  def 					UpperCAmelCase_					(		self		)		->    List[str]:






        """simple docstring"""





        _snake_case  ,				_snake_case		:						Union[str, Any]         =  self.model_tester.prepare_config_and_inputs_for_common()
        _snake_case		:						Dict         =  True

        _snake_case		:						List[Any]         =  getattr(self.model_tester  ,  '''seq_length'''  ,  _A		)
        _snake_case		:						List[str]         =  getattr(self.model_tester  ,  '''encoder_seq_length'''  ,  _A		)
        _snake_case		:						Any         =  getattr(self.model_tester  ,  '''key_length'''  ,  _A		)
        _snake_case		:						List[str]         =  getattr(self.model_tester  ,  '''chunk_length'''  ,  _A		)

        if chunk_length is not None and hasattr(self.model_tester  ,  '''num_hashes'''		):
              _snake_case		:						int         =  encoder_seq_length * self.model_tester.num_hashes

        for model_class in self.all_model_classes:
              _snake_case		:						Tuple         =  True
              _snake_case		:						Dict         =  False
              _snake_case		:						str         =  True
              _snake_case		:						int         =  model_class(_A		)
              model.to(_A		)
              model.eval()
              with torch.no_grad():
                    _snake_case		:						int         =  model(**self._prepare_for_class(_A  ,  _A		)		)
              _snake_case		:						Optional[Any]         =  outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
              self.assertEqual(len(_A		)  ,  self.model_tester.num_attention_outputs		)

              # check that output_attentions also work using config
              del inputs_dict["output_attentions"]
              _snake_case		:						Optional[Any]         =  True
              _snake_case		:						Union[str, Any]         =  model_class(_A		)
              model.to(_A		)
              model.eval()
              with torch.no_grad():
                    _snake_case		:						Optional[Any]         =  model(**self._prepare_for_class(_A  ,  _A		)		)
              _snake_case		:						List[Any]         =  outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
              self.assertEqual(len(_A		)  ,  self.model_tester.num_attention_outputs		)

              if chunk_length is not None:
                    self.assertListEqual(
                        list(attentions[0].shape[-4:]		)  ,  [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length]  ,  )
              else:
                    self.assertListEqual(
                        list(attentions[0].shape[-3:]		)  ,  [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]  ,  )




def  _a     (				):





      """simple docstring"""



      _snake_case		:						str         =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
      return image





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







  @cached_property
  def 					UpperCAmelCase_					(		self		)		->    Dict:






        """simple docstring"""





        return (
            EfficientFormerImageProcessor.from_pretrained('''snap-research/efficientformer-l1-300'''		)
            if is_vision_available()
            else None
        )







  @slow
  def 					UpperCAmelCase_					(		self		)		->    Union[str, Any]:






        """simple docstring"""





        _snake_case		:						str         =  EfficientFormerForImageClassification.from_pretrained('''snap-research/efficientformer-l1-300'''		).to(
            _A		)

        _snake_case		:						Optional[int]         =  self.default_image_processor
        _snake_case		:						List[str]         =  prepare_img()
        _snake_case		:						List[Any]         =  image_processor(images=_A  ,  return_tensors='''pt'''		).to(_A		)

        # forward pass
        with torch.no_grad():
              _snake_case		:						int         =  model(**_A		)

        # verify the logits
        _snake_case		:						int         =  (1, 1_000)
        self.assertEqual(outputs.logits.shape  ,  _A		)

        _snake_case		:						Optional[Any]         =  torch.tensor([-0.0_555, 0.4_825, -0.0_852]		).to(_A		)
        self.assertTrue(torch.allclose(outputs.logits[0][:3]  ,  _A  ,  atol=1E-4		)		)







  @slow
  def 					UpperCAmelCase_					(		self		)		->    Optional[int]:






        """simple docstring"""





        _snake_case		:						Tuple         =  EfficientFormerForImageClassificationWithTeacher.from_pretrained(
            '''snap-research/efficientformer-l1-300'''		).to(_A		)

        _snake_case		:						str         =  self.default_image_processor
        _snake_case		:						Union[str, Any]         =  prepare_img()
        _snake_case		:						Optional[Any]         =  image_processor(images=_A  ,  return_tensors='''pt'''		).to(_A		)

        # forward pass
        with torch.no_grad():
              _snake_case		:						str         =  model(**_A		)

        # verify the logits
        _snake_case		:						Optional[Any]         =  (1, 1_000)
        self.assertEqual(outputs.logits.shape  ,  _A		)

        _snake_case		:						List[str]         =  torch.tensor([-0.1_312, 0.4_353, -1.0_499]		).to(_A		)
        self.assertTrue(torch.allclose(outputs.logits[0][:3]  ,  _A  ,  atol=1E-4		)		)





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 normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


UpperCamelCase__	:   Union[str, Any]								=     logging.get_logger(__name__)



class    __snake_case	(     lowerCAmelCase__							):
  __lowerCAmelCase  :						Tuple    			=	['pixel_values']

  def __init__(       self    ,		_A = True    ,		_A = None    ,		_A = PILImageResampling.BILINEAR    ,		_A = True    ,		_A = 1 / 255    ,		_A = True    ,		_A = None    ,		_A = None    ,		**_A    ,		):
      super().__init__(**_A)
      SCREAMING_SNAKE_CASE_						=    size if size is not None else {'height': 224, 'width': 224}
      SCREAMING_SNAKE_CASE_						=    get_size_dict(_A)
      SCREAMING_SNAKE_CASE_						=    do_resize
      SCREAMING_SNAKE_CASE_						=    do_rescale
      SCREAMING_SNAKE_CASE_						=    do_normalize
      SCREAMING_SNAKE_CASE_						=    size
      SCREAMING_SNAKE_CASE_						=    resample
      SCREAMING_SNAKE_CASE_						=    rescale_factor
      SCREAMING_SNAKE_CASE_						=    image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
      SCREAMING_SNAKE_CASE_						=    image_std if image_std is not None else IMAGENET_STANDARD_STD

  def     lowerCAmelCase__  (       self    ,		_A    ,		_A    ,		_A = PILImageResampling.BILINEAR    ,		_A = None    ,		**_A    ,		):
      SCREAMING_SNAKE_CASE_						=    get_size_dict(_A)
      if "height" not in size or "width" not in size:
          raise ValueError(f"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}""")
      return resize(
          _A    ,		size=(size['height'], size['width'])    ,		resample=_A    ,		data_format=_A    ,		**_A)

  def     lowerCAmelCase__  (       self    ,		_A    ,		_A    ,		_A = None    ,		**_A):
      return rescale(_A    ,		scale=_A    ,		data_format=_A    ,		**_A)

  def     lowerCAmelCase__  (       self    ,		_A    ,		_A    ,		_A    ,		_A = None    ,		**_A    ,		):
      return normalize(_A    ,		mean=_A    ,		std=_A    ,		data_format=_A    ,		**_A)


  def     lowerCAmelCase__  (       self    ,		_A    ,		_A = None    ,		_A = None    ,		_A = None    ,		_A = None    ,		_A = None    ,		_A = None    ,		_A = None    ,		_A = None    ,		_A = None    ,		_A = ChannelDimension.FIRST    ,		**_A    ,		):
      SCREAMING_SNAKE_CASE_						=    do_resize if do_resize is not None else self.do_resize
      SCREAMING_SNAKE_CASE_						=    do_rescale if do_rescale is not None else self.do_rescale
      SCREAMING_SNAKE_CASE_						=    do_normalize if do_normalize is not None else self.do_normalize
      SCREAMING_SNAKE_CASE_						=    resample if resample is not None else self.resample
      SCREAMING_SNAKE_CASE_						=    rescale_factor if rescale_factor is not None else self.rescale_factor
      SCREAMING_SNAKE_CASE_						=    image_mean if image_mean is not None else self.image_mean
      SCREAMING_SNAKE_CASE_						=    image_std if image_std is not None else self.image_std

      SCREAMING_SNAKE_CASE_						=    size if size is not None else self.size
      SCREAMING_SNAKE_CASE_						=    get_size_dict(_A)

      SCREAMING_SNAKE_CASE_						=    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_rescale and rescale_factor is None:
          raise ValueError('Rescale factor must be specified if do_rescale is True.')

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

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

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

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

      SCREAMING_SNAKE_CASE_						=    [to_channel_dimension_format(_A    ,		_A) for image in images]

      SCREAMING_SNAKE_CASE_						=    {'pixel_values': images}
      return BatchFeature(data=_A    ,		tensor_type=_A)


