




import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from PIL import Image
from torchvision.transforms import (
    CenterCrop,
    Compose,
    Normalize,
    RandomHorizontalFlip,
    RandomResizedCrop,
    Resize,
    ToTensor,
)

import transformers
from transformers import (
    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    AutoModelForImageClassification,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
__a          =			logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('4.31.0')

require_version('datasets>=1.8.0', 'To fix: pip install -r examples/pytorch/image-classification/requirements.txt')

__a          =			list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
__a          =			tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     with open(UpperCAmelCase__			,						'''rb'''				) as f:
          UpperCAmelCase_      :							Union[str, Any]       =      Image.open(UpperCAmelCase__				)
          return im.convert('''RGB'''				)

@dataclass
class   __a:






    """simple docstring"""





    lowerCAmelCase        =				field(
        default=_snake_case    ,						metadata={
            '''help''': '''Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'''
        }    ,						)
    lowerCAmelCase        =				field(
        default=_snake_case    ,						metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}       )
    lowerCAmelCase        =				field(default=_snake_case    ,						metadata={'''help''': '''A folder containing the training data.'''}       )
    lowerCAmelCase        =				field(default=_snake_case    ,						metadata={'''help''': '''A folder containing the validation data.'''}       )
    lowerCAmelCase        =				field(
        default=0.15    ,						metadata={'''help''': '''Percent to split off of train for validation.'''}       )
    lowerCAmelCase        =				field(
        default=_snake_case    ,						metadata={
            '''help''': (
                '''For debugging purposes or quicker training, truncate the number of training examples to this '''
                '''value if set.'''
            )
        }    ,						)
    lowerCAmelCase        =				field(
        default=_snake_case    ,						metadata={
            '''help''': (
                '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
                '''value if set.'''
            )
        }    ,						)





    def 							a__				(				self  )			->		List[str]:
         if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
              raise ValueError(
                  '''You must specify either a dataset name from the hub or a train and/or validation directory.'''  )


@dataclass
class   __a:






    """simple docstring"""





    lowerCAmelCase        =				field(
        default='''google/vit-base-patch16-224-in21k'''    ,						metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}    ,						)
    lowerCAmelCase        =				field(
        default=_snake_case    ,						metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(_snake_case       )}    ,						)
    lowerCAmelCase        =				field(
        default=_snake_case    ,						metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}       )
    lowerCAmelCase        =				field(
        default=_snake_case    ,						metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''}       )
    lowerCAmelCase        =				field(
        default='''main'''    ,						metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}    ,						)
    lowerCAmelCase        =				field(default=_snake_case    ,						metadata={'''help''': '''Name or path of preprocessor config.'''}       )
    lowerCAmelCase        =				field(
        default=_snake_case    ,						metadata={
            '''help''': (
                '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
                '''with private models).'''
            )
        }    ,						)
    lowerCAmelCase        =				field(
        default=_snake_case    ,						metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''}    ,						)







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     UpperCAmelCase_      :							Optional[int]       =      torch.stack([example['''pixel_values'''] for example in examples]				)
     UpperCAmelCase_      :							Any       =      torch.tensor([example['''labels'''] for example in examples]				)
     return {"pixel_values": pixel_values, "labels": labels}







def lowerCamelCase__       (      ):

     '''simple docstring'''


     UpperCAmelCase_      :							Union[str, Any]       =      HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
     if len(sys.argv				) == 2 and sys.argv[1].endswith('''.json'''				):
          # If we pass only one argument to the script and it's the path to a json file,
          # let's parse it to get our arguments.
          UpperCAmelCase_,   UpperCAmelCase_,   UpperCAmelCase_      :							str       =      parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
     else:
          UpperCAmelCase_,   UpperCAmelCase_,   UpperCAmelCase_      :							Optional[int]       =      parser.parse_args_into_dataclasses()

     # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
     # information sent is the one passed as arguments along with your Python/PyTorch versions.
     send_example_telemetry('''run_image_classification'''			,						UpperCAmelCase__			,						UpperCAmelCase__				)

     # Setup logging
     logging.basicConfig(
         format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''			,						datefmt='''%m/%d/%Y %H:%M:%S'''			,						handlers=[logging.StreamHandler(sys.stdout				)]			,						)

     if training_args.should_log:
          # The default of training_args.log_level is passive, so we set log level at info here to have that default.
          transformers.utils.logging.set_verbosity_info()

     UpperCAmelCase_      :							str       =      training_args.get_process_log_level()
     logger.setLevel(UpperCAmelCase__				)
     transformers.utils.logging.set_verbosity(UpperCAmelCase__				)
     transformers.utils.logging.enable_default_handler()
     transformers.utils.logging.enable_explicit_format()

     # Log on each process the small summary:
     logger.warning(
         f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
         + f'''distributed training: {bool(training_args.local_rank != -1				)}, 16-bits training: {training_args.fpaa}'''				)
     logger.info(f'''Training/evaluation parameters {training_args}'''				)

     # Detecting last checkpoint.
     UpperCAmelCase_      :							Tuple       =      None
     if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
          UpperCAmelCase_      :							Union[str, Any]       =      get_last_checkpoint(training_args.output_dir				)
          if last_checkpoint is None and len(os.listdir(training_args.output_dir				)				) > 0:
               raise ValueError(
                   f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                   '''Use --overwrite_output_dir to overcome.'''				)
          elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
               logger.info(
                   f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                   '''the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'''				)

    # Set seed before initializing model.
     set_seed(training_args.seed				)

     # Initialize our dataset and prepare it for the 'image-classification' task.
     if data_args.dataset_name is not None:
          UpperCAmelCase_      :							Union[str, Any]       =      load_dataset(
              data_args.dataset_name			,						data_args.dataset_config_name			,						cache_dir=model_args.cache_dir			,						task='''image-classification'''			,						use_auth_token=True if model_args.use_auth_token else None			,						)
     else:
          UpperCAmelCase_      :							Any       =      {}
          if data_args.train_dir is not None:
               UpperCAmelCase_      :							List[Any]       =      os.path.join(data_args.train_dir			,						'''**'''				)
          if data_args.validation_dir is not None:
               UpperCAmelCase_      :							Optional[Any]       =      os.path.join(data_args.validation_dir			,						'''**'''				)
          UpperCAmelCase_      :							Tuple       =      load_dataset(
              '''imagefolder'''			,						data_files=UpperCAmelCase__			,						cache_dir=model_args.cache_dir			,						task='''image-classification'''			,						)

     # If we don't have a validation split, split off a percentage of train as validation.
     UpperCAmelCase_      :							List[str]       =      None if '''validation''' in dataset.keys() else data_args.train_val_split
     if isinstance(data_args.train_val_split			,						UpperCAmelCase__				) and data_args.train_val_split > 0.0:
          UpperCAmelCase_      :							Optional[Any]       =      dataset['''train'''].train_test_split(data_args.train_val_split				)
          UpperCAmelCase_      :							Optional[Any]       =      split['''train''']
          UpperCAmelCase_      :							Dict       =      split['''test''']

     # Prepare label mappings.
     # We'll include these in the model's config to get human readable labels in the Inference API.
     UpperCAmelCase_      :							Union[str, Any]       =      dataset['''train'''].features['''labels'''].names
     UpperCAmelCase_,   UpperCAmelCase_      :							Optional[Any]       =      {}, {}
     for i, label in enumerate(UpperCAmelCase__				):
          UpperCAmelCase_      :							Dict       =      str(UpperCAmelCase__				)
          UpperCAmelCase_      :							Union[str, Any]       =      label

     # Load the accuracy metric from the datasets package
     UpperCAmelCase_      :							Optional[Any]       =      evaluate.load('''accuracy'''				)

     # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
     # predictions and label_ids field) and has to return a dictionary string to float.
     def compute_metrics(_lowercase				):
          return metric.compute(predictions=np.argmax(p.predictions			,						axis=1				)			,						references=p.label_ids				)

     UpperCAmelCase_      :							Tuple       =      AutoConfig.from_pretrained(
         model_args.config_name or model_args.model_name_or_path			,						num_labels=len(UpperCAmelCase__				)			,						labelaid=UpperCAmelCase__			,						idalabel=UpperCAmelCase__			,						finetuning_task='''image-classification'''			,						cache_dir=model_args.cache_dir			,						revision=model_args.model_revision			,						use_auth_token=True if model_args.use_auth_token else None			,						)
     UpperCAmelCase_      :							Optional[int]       =      AutoModelForImageClassification.from_pretrained(
         model_args.model_name_or_path			,						from_tf=bool('''.ckpt''' in model_args.model_name_or_path				)			,						config=UpperCAmelCase__			,						cache_dir=model_args.cache_dir			,						revision=model_args.model_revision			,						use_auth_token=True if model_args.use_auth_token else None			,						ignore_mismatched_sizes=model_args.ignore_mismatched_sizes			,						)
     UpperCAmelCase_      :							Dict       =      AutoImageProcessor.from_pretrained(
         model_args.image_processor_name or model_args.model_name_or_path			,						cache_dir=model_args.cache_dir			,						revision=model_args.model_revision			,						use_auth_token=True if model_args.use_auth_token else None			,						)

     # Define torchvision transforms to be applied to each image.
     if "shortest_edge" in image_processor.size:
          UpperCAmelCase_      :							Union[str, Any]       =      image_processor.size['''shortest_edge''']
     else:
          UpperCAmelCase_      :							Any       =      (image_processor.size['''height'''], image_processor.size['''width'''])
     UpperCAmelCase_      :							Tuple       =      Normalize(mean=image_processor.image_mean			,						std=image_processor.image_std				)
     UpperCAmelCase_      :							List[str]       =      Compose(
         [
             RandomResizedCrop(UpperCAmelCase__				),
             RandomHorizontalFlip(),
             ToTensor(),
             normalize,
         ]				)
     UpperCAmelCase_      :							List[str]       =      Compose(
         [
             Resize(UpperCAmelCase__				),
             CenterCrop(UpperCAmelCase__				),
             ToTensor(),
             normalize,
         ]				)

     def train_transforms(_lowercase				):
          UpperCAmelCase_      :							List[str]       =      [
              _train_transforms(pil_img.convert('''RGB'''				)				) for pil_img in example_batch['''image''']
          ]
          return example_batch

     def val_transforms(_lowercase				):
          UpperCAmelCase_      :							int       =      [_val_transforms(pil_img.convert('''RGB'''				)				) for pil_img in example_batch['''image''']]
          return example_batch

     if training_args.do_train:
          if "train" not in dataset:
               raise ValueError('''--do_train requires a train dataset'''				)
          if data_args.max_train_samples is not None:
               UpperCAmelCase_      :							Optional[int]       =      (
                   dataset['''train'''].shuffle(seed=training_args.seed				).select(range(data_args.max_train_samples				)				)
               )
          # Set the training transforms
          dataset["train"].set_transform(UpperCAmelCase__				)

     if training_args.do_eval:
          if "validation" not in dataset:
               raise ValueError('''--do_eval requires a validation dataset'''				)
          if data_args.max_eval_samples is not None:
               UpperCAmelCase_      :							int       =      (
                   dataset['''validation'''].shuffle(seed=training_args.seed				).select(range(data_args.max_eval_samples				)				)
               )
          # Set the validation transforms
          dataset["validation"].set_transform(UpperCAmelCase__				)

     # Initalize our trainer
     UpperCAmelCase_      :							List[str]       =      Trainer(
         model=UpperCAmelCase__			,						args=UpperCAmelCase__			,						train_dataset=dataset['''train'''] if training_args.do_train else None			,						eval_dataset=dataset['''validation'''] if training_args.do_eval else None			,						compute_metrics=UpperCAmelCase__			,						tokenizer=UpperCAmelCase__			,						data_collator=UpperCAmelCase__			,						)

     # Training
     if training_args.do_train:
          UpperCAmelCase_      :							Optional[Any]       =      None
          if training_args.resume_from_checkpoint is not None:
               UpperCAmelCase_      :							Union[str, Any]       =      training_args.resume_from_checkpoint
          elif last_checkpoint is not None:
               UpperCAmelCase_      :							Tuple       =      last_checkpoint
          UpperCAmelCase_      :							List[str]       =      trainer.train(resume_from_checkpoint=UpperCAmelCase__				)
          trainer.save_model()
          trainer.log_metrics('''train'''			,						train_result.metrics				)
          trainer.save_metrics('''train'''			,						train_result.metrics				)
          trainer.save_state()

     # Evaluation
     if training_args.do_eval:
          UpperCAmelCase_      :							Optional[int]       =      trainer.evaluate()
          trainer.log_metrics('''eval'''			,						UpperCAmelCase__				)
          trainer.save_metrics('''eval'''			,						UpperCAmelCase__				)

     # Write model card and (optionally) push to hub
     UpperCAmelCase_      :							Any       =      {
         '''finetuned_from''': model_args.model_name_or_path,
         '''tasks''': '''image-classification''',
         '''dataset''': data_args.dataset_name,
         '''tags''': ['''image-classification''', '''vision'''],
     }
     if training_args.push_to_hub:
          trainer.push_to_hub(**UpperCAmelCase__				)
     else:
          trainer.create_model_card(**UpperCAmelCase__				)


if __name__ == "__main__":
       main()





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


if is_vision_available():
     import PIL


__a          =			logging.get_logger(__name__)







def lowerCamelCase__       (      _lowercase				):

     '''simple docstring'''


     if isinstance(_lowercase			,						(list, tuple)				) and isinstance(videos[0]			,						(list, tuple)				) and is_valid_image(videos[0][0]				):
          return videos

     elif isinstance(_lowercase			,						(list, tuple)				) and is_valid_image(videos[0]				):
          return [videos]

     elif is_valid_image(_lowercase				):
          return [[videos]]

     raise ValueError(f'''Could not make batched video from {videos}'''				)



class   __a(					_a       ):






    """simple docstring"""





    lowerCAmelCase        =				['''pixel_values''']





    def __init__(				self       ,_SCREAMING_SNAKE_CASE = True       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR       ,_SCREAMING_SNAKE_CASE = True       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = True       ,_SCREAMING_SNAKE_CASE = 1 / 255       ,_SCREAMING_SNAKE_CASE = True       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,**_SCREAMING_SNAKE_CASE       ,)			->		None:
         super().__init__(**_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							int       =      size if size is not None else {'''shortest_edge''': 224}
         UpperCAmelCase_      :							Any       =      get_size_dict(_SCREAMING_SNAKE_CASE       ,default_to_square=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							Any       =      crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
         UpperCAmelCase_      :							List[str]       =      get_size_dict(_SCREAMING_SNAKE_CASE       ,param_name='''crop_size'''  )

         UpperCAmelCase_      :							str       =      do_resize
         UpperCAmelCase_      :							Union[str, Any]       =      size
         UpperCAmelCase_      :							int       =      do_center_crop
         UpperCAmelCase_      :							List[str]       =      crop_size
         UpperCAmelCase_      :							Optional[int]       =      resample
         UpperCAmelCase_      :							List[Any]       =      do_rescale
         UpperCAmelCase_      :							Tuple       =      rescale_factor
         UpperCAmelCase_      :							Optional[Any]       =      do_normalize
         UpperCAmelCase_      :							int       =      image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
         UpperCAmelCase_      :							Optional[int]       =      image_std if image_std is not None else IMAGENET_STANDARD_STD





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE = PILImageResampling.BILINEAR       ,_SCREAMING_SNAKE_CASE = None       ,**_SCREAMING_SNAKE_CASE       ,)			->		np.ndarray:
         UpperCAmelCase_      :							Optional[int]       =      get_size_dict(_SCREAMING_SNAKE_CASE       ,default_to_square=_SCREAMING_SNAKE_CASE  )
         if "shortest_edge" in size:
              UpperCAmelCase_      :							Dict       =      get_resize_output_image_size(_SCREAMING_SNAKE_CASE       ,size['''shortest_edge''']       ,default_to_square=_SCREAMING_SNAKE_CASE  )
         elif "height" in size and "width" in size:
              UpperCAmelCase_      :							Tuple       =      (size['''height'''], size['''width'''])
         else:
              raise ValueError(f'''Size must have \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'''  )
         return resize(_SCREAMING_SNAKE_CASE       ,size=_SCREAMING_SNAKE_CASE       ,resample=_SCREAMING_SNAKE_CASE       ,data_format=_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE = None       ,**_SCREAMING_SNAKE_CASE       ,)			->		np.ndarray:
         UpperCAmelCase_      :							str       =      get_size_dict(_SCREAMING_SNAKE_CASE  )
         if "height" not in size or "width" not in size:
              raise ValueError(f'''Size must have \'height\' and \'width\' as keys. Got {size.keys()}'''  )
         return center_crop(_SCREAMING_SNAKE_CASE       ,size=(size['''height'''], size['''width'''])       ,data_format=_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE = None       ,**_SCREAMING_SNAKE_CASE       ,)			->		Dict:
         return rescale(_SCREAMING_SNAKE_CASE       ,scale=_SCREAMING_SNAKE_CASE       ,data_format=_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE = None       ,**_SCREAMING_SNAKE_CASE       ,)			->		np.ndarray:
         return normalize(_SCREAMING_SNAKE_CASE       ,mean=_SCREAMING_SNAKE_CASE       ,std=_SCREAMING_SNAKE_CASE       ,data_format=_SCREAMING_SNAKE_CASE       ,**_SCREAMING_SNAKE_CASE  )





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = ChannelDimension.FIRST       ,)			->		np.ndarray:
         if do_resize and size is None or resample is None:
              raise ValueError('''Size and resample 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.'''  )

         # All transformations expect numpy arrays.
         UpperCAmelCase_      :							Any       =      to_numpy_array(_SCREAMING_SNAKE_CASE  )

         if do_resize:
              UpperCAmelCase_      :							Union[str, Any]       =      self.resize(image=_SCREAMING_SNAKE_CASE       ,size=_SCREAMING_SNAKE_CASE       ,resample=_SCREAMING_SNAKE_CASE  )

         if do_center_crop:
              UpperCAmelCase_      :							Optional[int]       =      self.center_crop(_SCREAMING_SNAKE_CASE       ,size=_SCREAMING_SNAKE_CASE  )

         if do_rescale:
              UpperCAmelCase_      :							str       =      self.rescale(image=_SCREAMING_SNAKE_CASE       ,scale=_SCREAMING_SNAKE_CASE  )

         if do_normalize:
              UpperCAmelCase_      :							List[Any]       =      self.normalize(image=_SCREAMING_SNAKE_CASE       ,mean=_SCREAMING_SNAKE_CASE       ,std=_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							Optional[int]       =      to_channel_dimension_format(_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE  )
         return image





    def 							a__				(				self       ,_SCREAMING_SNAKE_CASE       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = None       ,_SCREAMING_SNAKE_CASE = ChannelDimension.FIRST       ,**_SCREAMING_SNAKE_CASE       ,)			->		PIL.Image.Image:
         UpperCAmelCase_      :							Dict       =      do_resize if do_resize is not None else self.do_resize
         UpperCAmelCase_      :							int       =      resample if resample is not None else self.resample
         UpperCAmelCase_      :							List[str]       =      do_center_crop if do_center_crop is not None else self.do_center_crop
         UpperCAmelCase_      :							Optional[Any]       =      do_rescale if do_rescale is not None else self.do_rescale
         UpperCAmelCase_      :							List[Any]       =      rescale_factor if rescale_factor is not None else self.rescale_factor
         UpperCAmelCase_      :							Tuple       =      do_normalize if do_normalize is not None else self.do_normalize
         UpperCAmelCase_      :							Optional[int]       =      image_mean if image_mean is not None else self.image_mean
         UpperCAmelCase_      :							Optional[int]       =      image_std if image_std is not None else self.image_std

         UpperCAmelCase_      :							List[str]       =      size if size is not None else self.size
         UpperCAmelCase_      :							Optional[int]       =      get_size_dict(_SCREAMING_SNAKE_CASE       ,default_to_square=_SCREAMING_SNAKE_CASE  )
         UpperCAmelCase_      :							List[str]       =      crop_size if crop_size is not None else self.crop_size
         UpperCAmelCase_      :							Any       =      get_size_dict(_SCREAMING_SNAKE_CASE       ,param_name='''crop_size'''  )

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

         UpperCAmelCase_      :							List[Any]       =      make_batched(_SCREAMING_SNAKE_CASE  )

         UpperCAmelCase_      :							str       =      [
             [
                 self._preprocess_image(
                     image=_SCREAMING_SNAKE_CASE       ,do_resize=_SCREAMING_SNAKE_CASE       ,size=_SCREAMING_SNAKE_CASE       ,resample=_SCREAMING_SNAKE_CASE       ,do_center_crop=_SCREAMING_SNAKE_CASE       ,crop_size=_SCREAMING_SNAKE_CASE       ,do_rescale=_SCREAMING_SNAKE_CASE       ,rescale_factor=_SCREAMING_SNAKE_CASE       ,do_normalize=_SCREAMING_SNAKE_CASE       ,image_mean=_SCREAMING_SNAKE_CASE       ,image_std=_SCREAMING_SNAKE_CASE       ,data_format=_SCREAMING_SNAKE_CASE       ,)
                 for img in video
             ]
             for video in videos
         ]

         UpperCAmelCase_      :							Any       =      {'''pixel_values''': videos}
         return BatchFeature(data=_SCREAMING_SNAKE_CASE       ,tensor_type=_SCREAMING_SNAKE_CASE  )