'''simple docstring'''


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'''):
 snake_case__	:     Optional[Any]      =    True
 from torch.cuda.amp import autocast


snake_case__	:     Tuple      =    logging.getLogger(__name__)






@dataclass
class 	__SCREAMING_SNAKE_CASE		:







  '''simple docstring'''






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







def    _lowerCamelCase       ( lowerCamelCase_   :				ModelArguments      ,	lowerCamelCase_   :				TrainingArguments  ):



     """simple docstring"""





     logging.basicConfig(
         format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'      ,	datefmt='%m/%d/%Y %H:%M:%S'      ,	handlers=[logging.StreamHandler(sys.stdout  )]      ,	)
     UpperCAmelCase_				:  Dict  = logging.WARNING
     if model_args.verbose_logging:
          UpperCAmelCase_				:  Union[str, Any]  = logging.DEBUG
     elif trainer_utils.is_main_process(training_args.local_rank  ):
          UpperCAmelCase_				:  Tuple  = logging.INFO
     logger.setLevel(lowerCamelCase_  )






@dataclass
class 	__SCREAMING_SNAKE_CASE		:







  '''simple docstring'''






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







@dataclass
class 	__SCREAMING_SNAKE_CASE		:







  '''simple docstring'''






  lowerCamelCase_						:bool		       =						False
  lowerCamelCase_						:Optional[str]		       =						None
  lowerCamelCase_						:Optional[str]		       =						"|"
  lowerCamelCase_						:Optional[Dict[str, str]]		       =						field(default_factory=lowerCamelCase_			)
  lowerCamelCase_						:Optional[Set[str]]		       =						field(default_factory=lowerCamelCase_			)
  lowerCamelCase_						:Optional[Callable[[str], str]]		       =						None


  @classmethod
  def _UpperCamelCase	(					cls ,						snake_case_		):




       '''simple docstring'''

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


  def _UpperCamelCase	(					self ,						snake_case_		):




       '''simple docstring'''

       if len(self.translation_table		) > 0:
            UpperCAmelCase_				:  str  = text.translate(self.translation_table		)
       if len(self.words_to_remove		) == 0:
            UpperCAmelCase_				:  List[Any]  = ' '.join(text.split()		)  # clean up whitespaces
       else:
            UpperCAmelCase_				:  str  = ' '.join(w for w in text.split() if w not in self.words_to_remove		)  # and clean up whilespaces
       return text






  def _UpperCamelCase	(					self ,						snake_case_		):




       '''simple docstring'''

       UpperCAmelCase_				:  Optional[Any]  = WavaVecaFeatureExtractor.from_pretrained(
           model_args.model_name_or_path ,						cache_dir=model_args.cache_dir		)
       if self.vocab_file:
            UpperCAmelCase_				:  str  = 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:
            UpperCAmelCase_				:  Tuple  = 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(snake_case_ ,						snake_case_		)







@dataclass
class 	__SCREAMING_SNAKE_CASE		:







  '''simple docstring'''






  lowerCamelCase_						:WavaVecaProcessor
  lowerCamelCase_						:Union[bool, str]		       =						True
  lowerCamelCase_						:Optional[int]		       =						None
  lowerCamelCase_						:Optional[int]		       =						None
  lowerCamelCase_						:Optional[int]		       =						None
  lowerCamelCase_						:Optional[int]		       =						None


  def __call__(					self ,						snake_case_		):




       '''simple docstring'''

       UpperCAmelCase_				:  List[str]  = [{'input_values': feature['input_values']} for feature in features]
       UpperCAmelCase_				:  Optional[Any]  = [{'input_ids': feature['labels']} for feature in features]

       UpperCAmelCase_				:  Tuple  = self.processor.pad(
           snake_case_ ,						padding=self.padding ,						max_length=self.max_length ,						pad_to_multiple_of=self.pad_to_multiple_of ,						return_tensors='pt' ,						)
       UpperCAmelCase_				:  Optional[int]  = self.processor.pad(
           labels=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
       UpperCAmelCase_				:  int  = labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1		) ,						-1_0_0		)

       UpperCAmelCase_				:  List[str]  = labels

       return batch







class 	__SCREAMING_SNAKE_CASE		(			lowerCamelCase_			):







  '''simple docstring'''






  def _UpperCamelCase	(					self ,						snake_case_ ,						snake_case_		):




       '''simple docstring'''

       model.train()
       UpperCAmelCase_				:  str  = self._prepare_inputs(snake_case_		)

       if self.use_amp:
            with autocast():
                 UpperCAmelCase_				:  List[Any]  = self.compute_loss(snake_case_ ,						snake_case_		)
       else:
            UpperCAmelCase_				:  Tuple  = self.compute_loss(snake_case_ ,						snake_case_		)

       if self.args.n_gpu > 1:
            if model.module.config.ctc_loss_reduction == "mean":
                 UpperCAmelCase_				:  List[Any]  = loss.mean()
            elif model.module.config.ctc_loss_reduction == "sum":
                 UpperCAmelCase_				:  Dict  = 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:
            UpperCAmelCase_				:  Union[str, Any]  = loss / self.args.gradient_accumulation_steps

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

       return loss.detach()







def    _lowerCamelCase       ( ):



     """simple docstring"""





     UpperCAmelCase_				:  List[Any]  = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)  )

     UpperCAmelCase_  ,     UpperCAmelCase_  ,     UpperCAmelCase_				:  Dict  = parser.parse_args_into_dataclasses()
     configure_logger(lowerCamelCase_      ,	lowerCamelCase_  )

     UpperCAmelCase_				:  Optional[Any]  = Orthography.from_name(data_args.orthography.lower()  )
     UpperCAmelCase_				:  Tuple  = orthography.create_processor(lowerCamelCase_  )
     UpperCAmelCase_				:  List[Any]  = 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  )      ,	)

     UpperCAmelCase_				:  Optional[Any]  = datasets.load_dataset(
         data_args.dataset_name      ,	data_args.dataset_config_name      ,	split=data_args.train_split_name  )
     UpperCAmelCase_				:  List[str]  = datasets.load_dataset(
         data_args.dataset_name      ,	data_args.dataset_config_name      ,	split=data_args.validation_split_name  )

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

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

     UpperCAmelCase_				:  List[str]  = train_dataset.map(lowerCamelCase_      ,	remove_columns=[data_args.speech_file_column]  )
     UpperCAmelCase_				:  Optional[Any]  = val_dataset.map(lowerCamelCase_      ,	remove_columns=[data_args.speech_file_column]  )

     if data_args.max_duration_in_seconds is not None:

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

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

     logger.warning(F'''Updated {len(lowerCamelCase_  )} 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}"'''  )
     UpperCAmelCase_				:  Optional[Any]  = None

     def prepare_dataset(lowerCamelCase_   :				List[str]  ):
          # 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}.'''

          UpperCAmelCase_				:  Union[str, Any]  = processor(
              audio=batch['speech']      ,	text=batch[data_args.target_text_column]      ,	sampling_rate=batch['sampling_rate'][0]  )
          batch.update(lowerCamelCase_  )
          return batch

     UpperCAmelCase_				:  List[str]  = train_dataset.map(
         lowerCamelCase_      ,	batch_size=training_args.per_device_train_batch_size      ,	batched=lowerCamelCase_      ,	num_proc=data_args.preprocessing_num_workers      ,	)
     UpperCAmelCase_				:  Union[str, Any]  = val_dataset.map(
         lowerCamelCase_      ,	batch_size=training_args.per_device_train_batch_size      ,	batched=lowerCamelCase_      ,	num_proc=data_args.preprocessing_num_workers      ,	)

     UpperCAmelCase_				:  List[str]  = DataCollatorCTCWithPadding(processor=lowerCamelCase_      ,	padding=lowerCamelCase_  )

     def compute_metrics(lowerCamelCase_   :				Dict  ):
          UpperCAmelCase_				:  int  = pred.predictions
          UpperCAmelCase_				:  Union[str, Any]  = np.argmax(lowerCamelCase_      ,	axis=-1  )

          UpperCAmelCase_				:  Dict  = processor.tokenizer.pad_token_id

          UpperCAmelCase_				:  Optional[int]  = processor.batch_decode(lowerCamelCase_  )
          # we do not want to group tokens when computing the metrics
          UpperCAmelCase_				:  Optional[int]  = processor.batch_decode(pred.label_ids      ,	group_tokens=lowerCamelCase_  )
          if logger.isEnabledFor(logging.DEBUG  ):
               for reference, predicted in zip(lowerCamelCase_      ,	lowerCamelCase_  ):
                    logger.debug(F'''reference: "{reference}"'''  )
                    logger.debug(F'''predicted: "{predicted}"'''  )
                    if orthography.untransliterator is not None:
                         logger.debug(F'''reference (untransliterated): "{orthography.untransliterator(lowerCamelCase_  )}"'''  )
                         logger.debug(F'''predicted (untransliterated): "{orthography.untransliterator(lowerCamelCase_  )}"'''  )

          UpperCAmelCase_				:  int  = wer_metric.compute(predictions=lowerCamelCase_      ,	references=lowerCamelCase_  )

          return {"wer": wer}

     if model_args.freeze_feature_extractor:
          model.freeze_feature_extractor()

     UpperCAmelCase_				:  str  = CTCTrainer(
         model=lowerCamelCase_      ,	data_collator=lowerCamelCase_      ,	args=lowerCamelCase_      ,	compute_metrics=lowerCamelCase_      ,	train_dataset=lowerCamelCase_      ,	eval_dataset=lowerCamelCase_      ,	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 ViltImageProcessor

class 						_SCREAMING_SNAKE_CASE				(  unittest.TestCase				):






		"""simple docstring"""







		def __init__(      self     :					Optional[int]	,       __SCREAMING_SNAKE_CASE     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					Union[str, Any]=7	,       __SCREAMING_SNAKE_CASE     :					Dict=3	,       __SCREAMING_SNAKE_CASE     :					Any=18	,       __SCREAMING_SNAKE_CASE     :					Optional[int]=30	,       __SCREAMING_SNAKE_CASE     :					int=400	,       __SCREAMING_SNAKE_CASE     :					int=True	,       __SCREAMING_SNAKE_CASE     :					Optional[int]=None	,       __SCREAMING_SNAKE_CASE     :					Any=2	,       __SCREAMING_SNAKE_CASE     :					Any=True	,       __SCREAMING_SNAKE_CASE     :					int=[0.5, 0.5, 0.5]	,       __SCREAMING_SNAKE_CASE     :					List[str]=[0.5, 0.5, 0.5]	,       ):






					"""simple docstring"""
					_snake_case														=   size if size is not None else {"shortest_edge": 30}
					_snake_case														=   parent
					_snake_case														=   batch_size
					_snake_case														=   num_channels
					_snake_case														=   image_size
					_snake_case														=   min_resolution
					_snake_case														=   max_resolution
					_snake_case														=   do_resize
					_snake_case														=   size
					_snake_case														=   size_divisor
					_snake_case														=   do_normalize
					_snake_case														=   image_mean
					_snake_case														=   image_std



		def 					_a					(      self     :					Optional[int] ):






					"""simple docstring"""
					return {
					    "image_mean": self.image_mean,
					    "image_std": self.image_std,
					    "do_normalize": self.do_normalize,
					    "do_resize": self.do_resize,
					    "size": self.size,
					    "size_divisor": self.size_divisor,
					}







		def 					_a					(      self     :					Any	,       __SCREAMING_SNAKE_CASE     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					List[Any]=False ):






					"""simple docstring"""
					if not batched:
								_snake_case														=   self.size["shortest_edge"]
								_snake_case														=   image_inputs[0]
								if isinstance(__SCREAMING_SNAKE_CASE	,       Image.Image ):
											_snake_case							,			_snake_case														=   image.size
								else:
											_snake_case							,			_snake_case														=   image.shape[1], image.shape[2]
								_snake_case														=   size / min(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE )
								if h < w:
											_snake_case							,			_snake_case														=   size, scale * w
								else:
											_snake_case							,			_snake_case														=   scale * h, size

								_snake_case														=   int((1_333 / 800) * size )
								if max(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE ) > max_size:
											_snake_case														=   max_size / max(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE )
											_snake_case														=   newh * scale
											_snake_case														=   neww * scale

								_snake_case							,			_snake_case														=   int(newh + 0.5 ), int(neww + 0.5 )
								_snake_case							,			_snake_case														=   (
								    newh // self.size_divisor * self.size_divisor,
								    neww // self.size_divisor * self.size_divisor,
								)

					else:
								_snake_case														=   []
								for image in image_inputs:
											_snake_case							,			_snake_case														=   self.get_expected_values([image] )
											expected_values.append((expected_height, expected_width) )
								_snake_case														=   max(__SCREAMING_SNAKE_CASE	,       key=lambda __SCREAMING_SNAKE_CASE : item[0] )[0]
								_snake_case														=   max(__SCREAMING_SNAKE_CASE	,       key=lambda __SCREAMING_SNAKE_CASE : item[1] )[1]

					return expected_height, expected_width

@require_torch
@require_vision
class 						_SCREAMING_SNAKE_CASE				(  _lowercase   ,  unittest.TestCase				):






		"""simple docstring"""







		A_    			=   ViltImageProcessor if is_vision_available() else None



		def 					_a					(      self     :					Tuple ):






					"""simple docstring"""
					_snake_case														=   ViltImageProcessingTester(self )



		@property
		def 					_a					(      self     :					List[Any] ):






					"""simple docstring"""
					return self.image_processor_tester.prepare_image_processor_dict()



		def 					_a					(      self     :					Optional[int] ):






					"""simple docstring"""
					_snake_case														=   self.image_processing_class(**self.image_processor_dict )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "image_mean" ) )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "image_std" ) )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "do_normalize" ) )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "do_resize" ) )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "size" ) )
					self.assertTrue(hasattr(__SCREAMING_SNAKE_CASE	,       "size_divisor" ) )



		def 					_a					(      self     :					Optional[Any] ):






					"""simple docstring"""
					_snake_case														=   self.image_processing_class.from_dict(self.image_processor_dict )
					self.assertEqual(image_processor.size	,       {"shortest_edge": 30} )

					_snake_case														=   self.image_processing_class.from_dict(self.image_processor_dict	,       size=42 )
					self.assertEqual(image_processor.size	,       {"shortest_edge": 42} )



		def 					_a					(      self     :					Dict ):






					"""simple docstring"""
					pass



		def 					_a					(      self     :					List[Any] ):






					"""simple docstring"""
					# Initialize image_processing
					_snake_case														=   self.image_processing_class(**self.image_processor_dict )
					# create random PIL images
					_snake_case														=   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
					_snake_case														=   image_processing(image_inputs[0]	,       return_tensors="pt" ).pixel_values

					_snake_case							,			_snake_case														=   self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE )
					self.assertEqual(
					    encoded_images.shape	,       (1, self.image_processor_tester.num_channels, expected_height, expected_width)	,       )

					# Test batched
					_snake_case														=   image_processing(__SCREAMING_SNAKE_CASE	,       return_tensors="pt" ).pixel_values

					_snake_case							,			_snake_case														=   self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE	,       batched=__SCREAMING_SNAKE_CASE )
					self.assertEqual(
					    encoded_images.shape	,       (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_channels,
					        expected_height,
					        expected_width,
					    )	,       )



		def 					_a					(      self     :					List[Any] ):






					"""simple docstring"""
					# Initialize image_processing
					_snake_case														=   self.image_processing_class(**self.image_processor_dict )
					# create random numpy tensors
					_snake_case														=   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
					_snake_case														=   image_processing(image_inputs[0]	,       return_tensors="pt" ).pixel_values

					_snake_case							,			_snake_case														=   self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE )
					self.assertEqual(
					    encoded_images.shape	,       (1, self.image_processor_tester.num_channels, expected_height, expected_width)	,       )

					# Test batched
					_snake_case														=   image_processing(__SCREAMING_SNAKE_CASE	,       return_tensors="pt" ).pixel_values

					_snake_case							,			_snake_case														=   self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE	,       batched=__SCREAMING_SNAKE_CASE )
					self.assertEqual(
					    encoded_images.shape	,       (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_channels,
					        expected_height,
					        expected_width,
					    )	,       )







		def 					_a					(      self     :					Dict ):






					"""simple docstring"""
					# Initialize image_processing
					_snake_case														=   self.image_processing_class(**self.image_processor_dict )
					# create random PyTorch tensors
					_snake_case														=   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
					_snake_case														=   image_processing(image_inputs[0]	,       return_tensors="pt" ).pixel_values

					_snake_case							,			_snake_case														=   self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE )
					self.assertEqual(
					    encoded_images.shape	,       (1, self.image_processor_tester.num_channels, expected_height, expected_width)	,       )

					# Test batched
					_snake_case														=   image_processing(__SCREAMING_SNAKE_CASE	,       return_tensors="pt" ).pixel_values

					_snake_case							,			_snake_case														=   self.image_processor_tester.get_expected_values(__SCREAMING_SNAKE_CASE	,       batched=__SCREAMING_SNAKE_CASE )
					self.assertEqual(
					    encoded_images.shape	,       (
					        self.image_processor_tester.batch_size,
					        self.image_processor_tester.num_channels,
					        expected_height,
					        expected_width,
					    )	,       )

