


import logging
import pathlib
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Set, Union

import datasets
import librosa
import numpy as np
import torch
from lang_trans import arabic
from packaging import version
from torch import nn

from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    trainer_utils,
)


if is_apex_available():
   from apex import amp

if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
   _A		:					Optional[int]          =							True
   from torch.cuda.amp import autocast


_A		:					str          =							logging.getLogger(__name__)



@dataclass
class 							a       :
     UpperCAmelCase__			:	str       =						field(
         metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} )
     UpperCAmelCase__			:	Optional[str]       =						field(
         default=_UpperCAmelCase  ,metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}  ,)
     UpperCAmelCase__			:	Optional[bool]       =						field(
         default=_UpperCAmelCase  ,metadata={"help": "Whether to freeze the feature extractor layers of the model."} )
     UpperCAmelCase__			:	Optional[bool]       =						field(
         default=_UpperCAmelCase  ,metadata={"help": "Whether to log verbose messages or not."}  ,)



def      __lowerCAmelCase    (				snake_case						:     ModelArguments    ,   snake_case						:     TrainingArguments			)							->				Dict:
   logging.basicConfig(
       format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s"""    ,   datefmt="""%m/%d/%Y %H:%M:%S"""    ,   handlers=[logging.StreamHandler(sys.stdout			)]    ,   )
   __lowerCamelCase:					Optional[Any]	 =						logging.WARNING
   if model_args.verbose_logging:
      __lowerCamelCase:					Tuple	 =						logging.DEBUG
   elif trainer_utils.is_main_process(training_args.local_rank			):
      __lowerCamelCase:					List[Any]	 =						logging.INFO
   logger.setLevel(snake_case			)



@dataclass
class 							a       :
     UpperCAmelCase__			:	str       =						field(
         default=_UpperCAmelCase  ,metadata={"help": "The name of the dataset to use (via the datasets library)."} )
     UpperCAmelCase__			:	Optional[str]       =						field(
         default=_UpperCAmelCase  ,metadata={"help": "The configuration name of the dataset to use (via the datasets library)."} )
     UpperCAmelCase__			:	Optional[str]       =						field(
         default="train"  ,metadata={
             "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
         }  ,)
     UpperCAmelCase__			:	Optional[str]       =						field(
         default="validation"  ,metadata={
             "help": (
                 "The name of the validation data set split to use (via the datasets library). Defaults to 'validation'"
             )
         }  ,)
     UpperCAmelCase__			:	Optional[str]       =						field(
         default="text"  ,metadata={"help": "Column in the dataset that contains label (target text). Defaults to 'text'"}  ,)
     UpperCAmelCase__			:	Optional[str]       =						field(
         default="file"  ,metadata={"help": "Column in the dataset that contains speech file path. Defaults to 'file'"}  ,)
     UpperCAmelCase__			:	Optional[bool]       =						field(
         default=_UpperCAmelCase  ,metadata={"help": "Resample loaded audio to target feature extractor's sampling rate or not."}  ,)
     UpperCAmelCase__			:	Optional[float]       =						field(
         default=_UpperCAmelCase  ,metadata={"help": "Filters out examples longer than specified. Defaults to no filtering."}  ,)
     UpperCAmelCase__			:	Optional[str]       =						field(
         default="librispeech"  ,metadata={
             "help": (
                 "Orthography used for normalization and tokenization: 'librispeech' (default), 'timit', or"
                 " 'buckwalter'."
             )
         }  ,)
     UpperCAmelCase__			:	bool       =						field(
         default=_UpperCAmelCase  ,metadata={"help": "Overwrite the cached preprocessed datasets or not."} )
     UpperCAmelCase__			:	Optional[int]       =						field(
         default=_UpperCAmelCase  ,metadata={"help": "The number of processes to use for the preprocessing."}  ,)



@dataclass
class 							a       :
     UpperCAmelCase__			:	bool       =						False
     UpperCAmelCase__			:	Optional[str]       =						None
     UpperCAmelCase__			:	Optional[str]       =						"|"
     UpperCAmelCase__			:	Optional[Dict[str, str]]       =						field(default_factory=_UpperCAmelCase )
     UpperCAmelCase__			:	Optional[Set[str]]       =						field(default_factory=_UpperCAmelCase )
     UpperCAmelCase__			:	Optional[Callable[[str], str]]       =						None





     @classmethod
     def 			SCREAMING_SNAKE_CASE__							(     cls       :					Tuple     ,						SCREAMING_SNAKE_CASE_       :					str				):
        if name == "librispeech":
           return cls()
        if name == "timit":
           return cls(
               do_lower_case=SCREAMING_SNAKE_CASE_     ,						translation_table=str.maketrans({"""-""": """ """}				)     ,						)
        if name == "buckwalter":
           __lowerCamelCase:					List[Any]	 =						{
               """-""": """ """,  # sometimes used to represent pauses
               """^""": """v""",  # fixing "tha" in arabic_speech_corpus dataset
           }
           return cls(
               vocab_file=pathlib.Path(SCREAMING_SNAKE_CASE_				).parent.joinpath("""vocab/buckwalter.json"""				)     ,						word_delimiter_token="""/"""     ,						translation_table=str.maketrans(SCREAMING_SNAKE_CASE_				)     ,						words_to_remove={"""sil"""}     ,						untransliterator=arabic.buckwalter.untransliterate     ,						)
        raise ValueError(F'Unsupported orthography: \'{name}\'.'				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Tuple     ,						SCREAMING_SNAKE_CASE_       :					str				):
        # TODO(elgeish) return a pipeline (e.g., from jiwer) instead? Or rely on branch predictor as is
        if len(self.translation_table				) > 0:
           __lowerCamelCase:					str	 =						text.translate(self.translation_table				)
        if len(self.words_to_remove				) == 0:
           __lowerCamelCase:					List[str]	 =						""" """.join(text.split()				)  # clean up whitespaces
        else:
           __lowerCamelCase:					Dict	 =						""" """.join(w for w in text.split() if w not in self.words_to_remove				)  # and clean up whilespaces
        return text







     def 			SCREAMING_SNAKE_CASE__							(     self       :					Tuple     ,						SCREAMING_SNAKE_CASE_       :					ModelArguments				):
        __lowerCamelCase:					str	 =						WavaVecaFeatureExtractor.from_pretrained(
            model_args.model_name_or_path     ,						cache_dir=model_args.cache_dir				)
        if self.vocab_file:
           __lowerCamelCase:					int	 =						WavaVecaCTCTokenizer(
               self.vocab_file     ,						cache_dir=model_args.cache_dir     ,						do_lower_case=self.do_lower_case     ,						word_delimiter_token=self.word_delimiter_token     ,						)
        else:
           __lowerCamelCase:					Union[str, Any]	 =						WavaVecaCTCTokenizer.from_pretrained(
               model_args.model_name_or_path     ,						cache_dir=model_args.cache_dir     ,						do_lower_case=self.do_lower_case     ,						word_delimiter_token=self.word_delimiter_token     ,						)
        return WavaVecaProcessor(SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_				)



@dataclass
class 							a       :
     UpperCAmelCase__			:	WavaVecaProcessor
     UpperCAmelCase__			:	Union[bool, str]       =						True
     UpperCAmelCase__			:	Optional[int]       =						None
     UpperCAmelCase__			:	Optional[int]       =						None
     UpperCAmelCase__			:	Optional[int]       =						None
     UpperCAmelCase__			:	Optional[int]       =						None





     def __call__(     self       :					Union[str, Any]     ,						SCREAMING_SNAKE_CASE_       :					List[Dict[str, Union[List[int], torch.Tensor]]]				):
        # split inputs and labels since they have to be of different lenghts and need
        # different padding methods
        __lowerCamelCase:					Optional[int]	 =						[{"""input_values""": feature["""input_values"""]} for feature in features]
        __lowerCamelCase:					Tuple	 =						[{"""input_ids""": feature["""labels"""]} for feature in features]

        __lowerCamelCase:					Tuple	 =						self.processor.pad(
            SCREAMING_SNAKE_CASE_     ,						padding=self.padding     ,						max_length=self.max_length     ,						pad_to_multiple_of=self.pad_to_multiple_of     ,						return_tensors="""pt"""     ,						)
        __lowerCamelCase:					Any	 =						self.processor.pad(
            labels=SCREAMING_SNAKE_CASE_     ,						padding=self.padding     ,						max_length=self.max_length_labels     ,						pad_to_multiple_of=self.pad_to_multiple_of_labels     ,						return_tensors="""pt"""     ,						)

        # replace padding with -100 to ignore loss correctly
        __lowerCamelCase:					List[str]	 =						labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1				)     ,						-100				)

        __lowerCamelCase:					Any	 =						labels

        return batch



class 							a       (      _UpperCAmelCase ):





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Union[str, Any]     ,						SCREAMING_SNAKE_CASE_       :					nn.Module     ,						SCREAMING_SNAKE_CASE_       :					Dict[str, Union[torch.Tensor, Any]]				):
        model.train()
        __lowerCamelCase:					Tuple	 =						self._prepare_inputs(SCREAMING_SNAKE_CASE_				)

        if self.use_amp:
           with autocast():
              __lowerCamelCase:					int	 =						self.compute_loss(SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_				)
        else:
           __lowerCamelCase:					Optional[int]	 =						self.compute_loss(SCREAMING_SNAKE_CASE_     ,						SCREAMING_SNAKE_CASE_				)

        if self.args.n_gpu > 1:
           if model.module.config.ctc_loss_reduction == "mean":
              __lowerCamelCase:					List[Any]	 =						loss.mean()
           elif model.module.config.ctc_loss_reduction == "sum":
              __lowerCamelCase:					Tuple	 =						loss.sum() / (inputs["""labels"""] >= 0).sum()
           else:
              raise ValueError(F'{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'				)

        if self.args.gradient_accumulation_steps > 1:
           __lowerCamelCase:					Union[str, Any]	 =						loss / self.args.gradient_accumulation_steps

        if self.use_amp:
           self.scaler.scale(SCREAMING_SNAKE_CASE_				).backward()
        elif self.use_apex:
           with amp.scale_loss(SCREAMING_SNAKE_CASE_     ,						self.optimizer				) as scaled_loss:
              scaled_loss.backward()
        elif self.deepspeed:
           self.deepspeed.backward(SCREAMING_SNAKE_CASE_				)
        else:
           loss.backward()

        return loss.detach()



def      __lowerCAmelCase    (				)							->				Union[str, Any]:
   # See all possible arguments in src/transformers/training_args.py
   # or by passing the --help flag to this script.
   # We now keep distinct sets of args, for a cleaner separation of concerns.

   __lowerCamelCase:					Dict	 =						HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)

   __lowerCamelCase ,  __lowerCamelCase ,  __lowerCamelCase:					int	 =						parser.parse_args_into_dataclasses()
   configure_logger(snake_case    ,   snake_case			)

   __lowerCamelCase:					Optional[int]	 =						Orthography.from_name(data_args.orthography.lower()			)
   __lowerCamelCase:					List[Any]	 =						orthography.create_processor(snake_case			)
   __lowerCamelCase:					str	 =						WavaVecaForCTC.from_pretrained(
       model_args.model_name_or_path    ,   cache_dir=model_args.cache_dir    ,   gradient_checkpointing=training_args.gradient_checkpointing    ,   vocab_size=len(processor.tokenizer			)    ,   )

   __lowerCamelCase:					Tuple	 =						datasets.load_dataset(
       data_args.dataset_name    ,   data_args.dataset_config_name    ,   split=data_args.train_split_name			)
   __lowerCamelCase:					Optional[Any]	 =						datasets.load_dataset(
       data_args.dataset_name    ,   data_args.dataset_config_name    ,   split=data_args.validation_split_name			)

   __lowerCamelCase:					str	 =						datasets.load_metric("""wer"""			)
   __lowerCamelCase:					Dict	 =						processor.feature_extractor.sampling_rate if data_args.target_feature_extractor_sampling_rate else None
   __lowerCamelCase:					int	 =						"""""".join(t for t in processor.tokenizer.get_vocab().keys() if len(snake_case			) == 1			)
   __lowerCamelCase:					int	 =						re.compile(  # remove characters not in vocabulary
       rf'[^\s{re.escape(snake_case			)}]'    ,   flags=re.IGNORECASE if processor.tokenizer.do_lower_case else 0    ,   )
   __lowerCamelCase:					Tuple	 =						[]

   def prepare_example(snake_case						:     Optional[Any]			):  # TODO(elgeish) make use of multiprocessing?
      __lowerCamelCase ,  __lowerCamelCase:					Union[str, Any]	 =						librosa.load(example[data_args.speech_file_column]    ,   sr=snake_case			)
      if data_args.max_duration_in_seconds is not None:
         __lowerCamelCase:					Optional[int]	 =						len(example["""speech"""]			) / example["""sampling_rate"""]
      # Normalize and clean up text; order matters!
      __lowerCamelCase:					str	 =						orthography.preprocess_for_training(example[data_args.target_text_column]			)
      __lowerCamelCase:					str	 =						vocabulary_text_cleaner.sub(""""""    ,   snake_case			)
      if updated_text != example[data_args.target_text_column]:
         text_updates.append((example[data_args.target_text_column], updated_text)			)
         __lowerCamelCase:					str	 =						updated_text
      return example

   __lowerCamelCase:					List[Any]	 =						train_dataset.map(snake_case    ,   remove_columns=[data_args.speech_file_column]			)
   __lowerCamelCase:					List[Any]	 =						val_dataset.map(snake_case    ,   remove_columns=[data_args.speech_file_column]			)

   if data_args.max_duration_in_seconds is not None:

      def filter_by_max_duration(snake_case						:     Optional[Any]			):
         return example["duration_in_seconds"] <= data_args.max_duration_in_seconds

      __lowerCamelCase:					Dict	 =						len(snake_case			)
      __lowerCamelCase:					Optional[Any]	 =						len(snake_case			)
      __lowerCamelCase:					Any	 =						train_dataset.filter(snake_case    ,   remove_columns=["""duration_in_seconds"""]			)
      __lowerCamelCase:					List[str]	 =						val_dataset.filter(snake_case    ,   remove_columns=["""duration_in_seconds"""]			)
      if len(snake_case			) > old_train_size:
         logger.warning(
             f'Filtered out {len(snake_case			) - old_train_size} train example(s) longer than'
             f' {data_args.max_duration_in_seconds} second(s).'			)
      if len(snake_case			) > old_val_size:
         logger.warning(
             f'Filtered out {len(snake_case			) - old_val_size} validation example(s) longer than'
             f' {data_args.max_duration_in_seconds} second(s).'			)
   logger.info(f'Split sizes: {len(snake_case			)} train and {len(snake_case			)} validation.'			)

   logger.warning(f'Updated {len(snake_case			)} transcript(s) using \'{data_args.orthography}\' orthography rules.'			)
   if logger.isEnabledFor(logging.DEBUG			):
      for original_text, updated_text in text_updates:
         logger.debug(f'Updated text: "{original_text}" -> "{updated_text}"'			)
   __lowerCamelCase:					List[str]	 =						None

   def prepare_dataset(snake_case						:     int			):
      # check that all files have the correct sampling rate
      assert (
          len(set(batch["""sampling_rate"""]			)			) == 1
      ), f'Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'

      __lowerCamelCase:					List[Any]	 =						processor(
          audio=batch["""speech"""]    ,   text=batch[data_args.target_text_column]    ,   sampling_rate=batch["""sampling_rate"""][0]			)
      batch.update(snake_case			)
      return batch

   __lowerCamelCase:					Tuple	 =						train_dataset.map(
       snake_case    ,   batch_size=training_args.per_device_train_batch_size    ,   batched=snake_case    ,   num_proc=data_args.preprocessing_num_workers    ,   )
   __lowerCamelCase:					Tuple	 =						val_dataset.map(
       snake_case    ,   batch_size=training_args.per_device_train_batch_size    ,   batched=snake_case    ,   num_proc=data_args.preprocessing_num_workers    ,   )

   __lowerCamelCase:					Union[str, Any]	 =						DataCollatorCTCWithPadding(processor=snake_case    ,   padding=snake_case			)

   def compute_metrics(snake_case						:     Union[str, Any]			):
      __lowerCamelCase:					List[str]	 =						pred.predictions
      __lowerCamelCase:					List[Any]	 =						np.argmax(snake_case    ,   axis=-1			)

      __lowerCamelCase:					int	 =						processor.tokenizer.pad_token_id

      __lowerCamelCase:					List[str]	 =						processor.batch_decode(snake_case			)
      # we do not want to group tokens when computing the metrics
      __lowerCamelCase:					Union[str, Any]	 =						processor.batch_decode(pred.label_ids    ,   group_tokens=snake_case			)
      if logger.isEnabledFor(logging.DEBUG			):
         for reference, predicted in zip(snake_case    ,   snake_case			):
            logger.debug(f'reference: "{reference}"'			)
            logger.debug(f'predicted: "{predicted}"'			)
            if orthography.untransliterator is not None:
               logger.debug(f'reference (untransliterated): "{orthography.untransliterator(snake_case			)}"'			)
               logger.debug(f'predicted (untransliterated): "{orthography.untransliterator(snake_case			)}"'			)

      __lowerCamelCase:					Optional[int]	 =						wer_metric.compute(predictions=snake_case    ,   references=snake_case			)

      return {"wer": wer}

   if model_args.freeze_feature_extractor:
      model.freeze_feature_extractor()

   __lowerCamelCase:					List[str]	 =						CTCTrainer(
       model=snake_case    ,   data_collator=snake_case    ,   args=snake_case    ,   compute_metrics=snake_case    ,   train_dataset=snake_case    ,   eval_dataset=snake_case    ,   tokenizer=processor.feature_extractor    ,   )

   trainer.train()


if __name__ == "__main__":
   main()






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import MobileNetVaImageProcessor



class 							a       (      unittest.TestCase ):





     def __init__(     self       :					Optional[int]     ,						SCREAMING_SNAKE_CASE_       :					str     ,						SCREAMING_SNAKE_CASE_       :					List[str]=7     ,						SCREAMING_SNAKE_CASE_       :					Union[str, Any]=3     ,						SCREAMING_SNAKE_CASE_       :					List[Any]=18     ,						SCREAMING_SNAKE_CASE_       :					List[str]=30     ,						SCREAMING_SNAKE_CASE_       :					List[Any]=400     ,						SCREAMING_SNAKE_CASE_       :					Dict=True     ,						SCREAMING_SNAKE_CASE_       :					Any=None     ,						SCREAMING_SNAKE_CASE_       :					List[str]=True     ,						SCREAMING_SNAKE_CASE_       :					Any=None     ,						):
        __lowerCamelCase:					List[Any]	 =						size if size is not None else {"""shortest_edge""": 20}
        __lowerCamelCase:					Tuple	 =						crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
        __lowerCamelCase:					List[Any]	 =						parent
        __lowerCamelCase:					Optional[int]	 =						batch_size
        __lowerCamelCase:					str	 =						num_channels
        __lowerCamelCase:					Dict	 =						image_size
        __lowerCamelCase:					Tuple	 =						min_resolution
        __lowerCamelCase:					Union[str, Any]	 =						max_resolution
        __lowerCamelCase:					Tuple	 =						do_resize
        __lowerCamelCase:					List[str]	 =						size
        __lowerCamelCase:					int	 =						do_center_crop
        __lowerCamelCase:					Tuple	 =						crop_size







     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[Any]				):
        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_center_crop": self.do_center_crop,
            "crop_size": self.crop_size,
        }



@require_torch
@require_vision
class 							a       (      _UpperCAmelCase  ,unittest.TestCase ):
     UpperCAmelCase__			:	int       =						MobileNetVaImageProcessor if is_vision_available() else None





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[str]				):
        __lowerCamelCase:					Tuple	 =						MobileNetVaImageProcessingTester(self				)





     @property
     def 			SCREAMING_SNAKE_CASE__							(     self       :					str				):
        return self.image_processor_tester.prepare_image_processor_dict()





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[str]				):
        __lowerCamelCase:					List[Any]	 =						self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""do_resize"""				)				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""size"""				)				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""do_center_crop"""				)				)
        self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_     ,						"""center_crop"""				)				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Any				):
        __lowerCamelCase:					str	 =						self.image_processing_class.from_dict(self.image_processor_dict				)
        self.assertEqual(image_processor.size     ,						{"""shortest_edge""": 20}				)
        self.assertEqual(image_processor.crop_size     ,						{"""height""": 18, """width""": 18}				)

        __lowerCamelCase:					Optional[int]	 =						self.image_processing_class.from_dict(self.image_processor_dict     ,						size=42     ,						crop_size=84				)
        self.assertEqual(image_processor.size     ,						{"""shortest_edge""": 42}				)
        self.assertEqual(image_processor.crop_size     ,						{"""height""": 84, """width""": 84}				)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[Any]				):
        pass





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        # Initialize image_processing
        __lowerCamelCase:					List[str]	 =						self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        __lowerCamelCase:					str	 =						prepare_image_inputs(self.image_processor_tester     ,						equal_resolution=SCREAMING_SNAKE_CASE_				)
        for image in image_inputs:
           self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,						Image.Image				)

        # Test not batched input
        __lowerCamelCase:					Optional[Any]	 =						image_processing(image_inputs[0]     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)

        # Test batched
        __lowerCamelCase:					Tuple	 =						image_processing(SCREAMING_SNAKE_CASE_     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        # Initialize image_processing
        __lowerCamelCase:					Union[str, Any]	 =						self.image_processing_class(**self.image_processor_dict				)
        # create random numpy tensors
        __lowerCamelCase:					Tuple	 =						prepare_image_inputs(self.image_processor_tester     ,						equal_resolution=SCREAMING_SNAKE_CASE_     ,						numpify=SCREAMING_SNAKE_CASE_				)
        for image in image_inputs:
           self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,						np.ndarray				)

        # Test not batched input
        __lowerCamelCase:					List[Any]	 =						image_processing(image_inputs[0]     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)

        # Test batched
        __lowerCamelCase:					Optional[Any]	 =						image_processing(SCREAMING_SNAKE_CASE_     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)







     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        # Initialize image_processing
        __lowerCamelCase:					str	 =						self.image_processing_class(**self.image_processor_dict				)
        # create random PyTorch tensors
        __lowerCamelCase:					List[str]	 =						prepare_image_inputs(self.image_processor_tester     ,						equal_resolution=SCREAMING_SNAKE_CASE_     ,						torchify=SCREAMING_SNAKE_CASE_				)
        for image in image_inputs:
           self.assertIsInstance(SCREAMING_SNAKE_CASE_     ,						torch.Tensor				)

        # Test not batched input
        __lowerCamelCase:					Union[str, Any]	 =						image_processing(image_inputs[0]     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)

        # Test batched
        __lowerCamelCase:					Optional[int]	 =						image_processing(SCREAMING_SNAKE_CASE_     ,						return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape     ,						(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.crop_size["""height"""],
                self.image_processor_tester.crop_size["""width"""],
            )     ,						)


