






'''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"):
  __lowerCAmelCase					   =       True
  from torch.cuda.amp import autocast


__lowerCAmelCase					   =       logging.getLogger(__name__)




@dataclass
class      __SCREAMING_SNAKE_CASE					:


  """simple docstring"""


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





def 			__UpperCamelCase				(			lowercase_					:     ModelArguments      ,					lowercase_					:     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      )]      ,					)
       a_	    = logging.WARNING
       if model_args.verbose_logging:
              a_	    = logging.DEBUG
       elif trainer_utils.is_main_process(training_args.local_rank      ):
              a_	    = logging.INFO
       logger.setLevel(lowercase_      )




@dataclass
class      __SCREAMING_SNAKE_CASE					:


  """simple docstring"""


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





@dataclass
class      __SCREAMING_SNAKE_CASE					:


  """simple docstring"""


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







  @classmethod
  def       _a					( cls      ,  UpperCamelCase__  ):






         """simple docstring"""


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







  def       _a					( self      ,  UpperCamelCase__  ):






         """simple docstring"""


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







  def       _a					( self      ,  UpperCamelCase__  ):






         """simple docstring"""


         a_	    = WavaVecaFeatureExtractor.from_pretrained(
             model_args.model_name_or_path      ,  cache_dir=model_args.cache_dir  )
         if self.vocab_file:
                a_	    = 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:
                a_	    = 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(UpperCamelCase__      ,  UpperCamelCase__  )





@dataclass
class      __SCREAMING_SNAKE_CASE					:


  """simple docstring"""


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







  def __call__( self      ,  UpperCamelCase__  ):






         """simple docstring"""


         a_	    = [{'input_values': feature['input_values']} for feature in features]
         a_	    = [{'input_ids': feature['labels']} for feature in features]

         a_	    = self.processor.pad(
             UpperCamelCase__      ,  padding=self.padding      ,  max_length=self.max_length      ,  pad_to_multiple_of=self.pad_to_multiple_of      ,  return_tensors='pt'      ,  )
         a_	    = self.processor.pad(
             labels=UpperCamelCase__      ,  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
         a_	    = labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1  )      ,  -100  )

         a_	    = labels

         return batch





class      __SCREAMING_SNAKE_CASE					(__A					):


  """simple docstring"""


  def       _a					( self      ,  UpperCamelCase__      ,  UpperCamelCase__  ):






         """simple docstring"""


         model.train()
         a_	    = self._prepare_inputs(UpperCamelCase__  )

         if self.use_amp:
                with autocast():
                       a_	    = self.compute_loss(UpperCamelCase__      ,  UpperCamelCase__  )
         else:
                a_	    = self.compute_loss(UpperCamelCase__      ,  UpperCamelCase__  )

         if self.args.n_gpu > 1:
                if model.module.config.ctc_loss_reduction == "mean":
                       a_	    = loss.mean()
                elif model.module.config.ctc_loss_reduction == "sum":
                       a_	    = 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:
                a_	    = loss / self.args.gradient_accumulation_steps

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

         return loss.detach()





def 			__UpperCamelCase				(			):
       """simple docstring"""




       a_	    = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)      )

       a_    ,  a_    ,  a_	    = parser.parse_args_into_dataclasses()
       configure_logger(lowercase_      ,					lowercase_      )

       a_	    = Orthography.from_name(data_args.orthography.lower()      )
       a_	    = orthography.create_processor(lowercase_      )
       a_	    = 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      )      ,					)

       a_	    = datasets.load_dataset(
           data_args.dataset_name      ,					data_args.dataset_config_name      ,					split=data_args.train_split_name      )
       a_	    = datasets.load_dataset(
           data_args.dataset_name      ,					data_args.dataset_config_name      ,					split=data_args.validation_split_name      )

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

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

       a_	    = train_dataset.map(lowercase_      ,					remove_columns=[data_args.speech_file_column]      )
       a_	    = val_dataset.map(lowercase_      ,					remove_columns=[data_args.speech_file_column]      )

       if data_args.max_duration_in_seconds is not None:

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

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

       logger.warning(F'Updated {len(lowercase_      )} 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}"'      )
       a_	    = None

       def prepare_dataset(lowercase_					:     Optional[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}.'

              a_	    = processor(
                  audio=batch['speech']      ,					text=batch[data_args.target_text_column]      ,					sampling_rate=batch['sampling_rate'][0]      )
              batch.update(lowercase_      )
              return batch

       a_	    = train_dataset.map(
           lowercase_      ,					batch_size=training_args.per_device_train_batch_size      ,					batched=lowercase_      ,					num_proc=data_args.preprocessing_num_workers      ,					)
       a_	    = val_dataset.map(
           lowercase_      ,					batch_size=training_args.per_device_train_batch_size      ,					batched=lowercase_      ,					num_proc=data_args.preprocessing_num_workers      ,					)

       a_	    = DataCollatorCTCWithPadding(processor=lowercase_      ,					padding=lowercase_      )

       def compute_metrics(lowercase_					:     List[str]      ):
              a_	    = pred.predictions
              a_	    = np.argmax(lowercase_      ,					axis=-1      )

              a_	    = processor.tokenizer.pad_token_id

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

              a_	    = wer_metric.compute(predictions=lowercase_      ,					references=lowercase_      )

              return {"wer": wer}

       if model_args.freeze_feature_extractor:
              model.freeze_feature_extractor()

       a_	    = CTCTrainer(
           model=lowercase_      ,					data_collator=lowercase_      ,					args=lowercase_      ,					compute_metrics=lowercase_      ,					train_dataset=lowercase_      ,					eval_dataset=lowercase_      ,					tokenizer=processor.feature_extractor      ,					)

       trainer.train()


if __name__ == "__main__":
  main()












'''simple docstring'''







import random
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():
  import PIL

  from transformers import FlavaImageProcessor
  from transformers.image_utils import PILImageResampling
  from transformers.models.flava.image_processing_flava import (
      FLAVA_CODEBOOK_MEAN,
      FLAVA_CODEBOOK_STD,
      FLAVA_IMAGE_MEAN,
      FLAVA_IMAGE_STD,
  )
else:
  __lowerCAmelCase					   =       __lowerCAmelCase					   =       __lowerCAmelCase					   =       __lowerCAmelCase					   =       None




class      __SCREAMING_SNAKE_CASE					(unittest.TestCase					):


  """simple docstring"""


  def __init__( self      ,  UpperCamelCase__      ,  UpperCamelCase__=7      ,  UpperCamelCase__=3      ,  UpperCamelCase__=30      ,  UpperCamelCase__=400      ,  UpperCamelCase__=True      ,  UpperCamelCase__=None      ,  UpperCamelCase__=True      ,  UpperCamelCase__=None      ,  UpperCamelCase__=None      ,  UpperCamelCase__=True      ,  UpperCamelCase__=1 / 255      ,  UpperCamelCase__=True      ,  UpperCamelCase__=FLAVA_IMAGE_MEAN      ,  UpperCamelCase__=FLAVA_IMAGE_STD      ,  UpperCamelCase__=14      ,  UpperCamelCase__=75      ,  UpperCamelCase__=None      ,  UpperCamelCase__=16      ,  UpperCamelCase__=0.3      ,  UpperCamelCase__=None      ,  UpperCamelCase__=True      ,  UpperCamelCase__=None      ,  UpperCamelCase__=None      ,  UpperCamelCase__=True      ,  UpperCamelCase__=None      ,  UpperCamelCase__=True      ,  UpperCamelCase__=True      ,  UpperCamelCase__=FLAVA_CODEBOOK_MEAN      ,  UpperCamelCase__=FLAVA_CODEBOOK_STD      ,  ):






         """simple docstring"""


         a_	    = size if size is not None else {'height': 224, 'width': 224}
         a_	    = crop_size if crop_size is not None else {'height': 224, 'width': 224}
         a_	    = codebook_size if codebook_size is not None else {'height': 112, 'width': 112}
         a_	    = codebook_crop_size if codebook_crop_size is not None else {'height': 112, 'width': 112}

         a_	    = parent
         a_	    = batch_size
         a_	    = num_channels
         a_	    = do_resize
         a_	    = do_rescale
         a_	    = rescale_factor
         a_	    = min_resolution
         a_	    = max_resolution
         a_	    = size
         a_	    = resample if resample is not None else PILImageResampling.BICUBIC
         a_	    = do_normalize
         a_	    = image_mean
         a_	    = image_std
         a_	    = do_center_crop
         a_	    = crop_size

         a_	    = input_size_patches
         a_	    = total_mask_patches
         a_	    = mask_group_max_patches
         a_	    = mask_group_min_patches
         a_	    = mask_group_min_aspect_ratio
         a_	    = mask_group_max_aspect_ratio

         a_	    = codebook_do_resize
         a_	    = codebook_size
         a_	    = codebook_resample if codebook_resample is not None else PILImageResampling.LANCZOS
         a_	    = codebook_do_center_crop
         a_	    = codebook_crop_size
         a_	    = codebook_do_map_pixels
         a_	    = codebook_do_normalize
         a_	    = codebook_image_mean
         a_	    = codebook_image_std







  def       _a					( self  ):






         """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,
             "resample": self.resample,
             "do_rescale": self.do_rescale,
             "rescale_factor": self.rescale_factor,
             "do_center_crop": self.do_center_crop,
             "crop_size": self.crop_size,
             "input_size_patches": self.input_size_patches,
             "total_mask_patches": self.total_mask_patches,
             "mask_group_max_patches": self.mask_group_max_patches,
             "mask_group_min_patches": self.mask_group_min_patches,
             "mask_group_min_aspect_ratio": self.mask_group_min_aspect_ratio,
             "mask_group_max_aspect_ratio": self.mask_group_min_aspect_ratio,
             "codebook_do_resize": self.codebook_do_resize,
             "codebook_size": self.codebook_size,
             "codebook_resample": self.codebook_resample,
             "codebook_do_center_crop": self.codebook_do_center_crop,
             "codebook_crop_size": self.codebook_crop_size,
             "codebook_do_map_pixels": self.codebook_do_map_pixels,
             "codebook_do_normalize": self.codebook_do_normalize,
             "codebook_image_mean": self.codebook_image_mean,
             "codebook_image_std": self.codebook_image_std,
         }







  def       _a					( self  ):






         """simple docstring"""


         return (self.size["height"], self.size["width"])







  def       _a					( self  ):






         """simple docstring"""


         return (
             (self.input_size_patches, self.input_size_patches)
             if not isinstance(self.input_size_patches      ,  UpperCamelCase__  )
             else self.input_size_patches
         )







  def       _a					( self  ):






         """simple docstring"""


         return (self.codebook_size["height"], self.codebook_size["width"])





@require_torch
@require_vision
class      __SCREAMING_SNAKE_CASE					(__A       ,					unittest.TestCase					):


  """simple docstring"""


  _a     :   Union[str, Any]			 =    FlavaImageProcessor if is_vision_available() else None
  _a     :   Dict			 =    None







  def       _a					( self  ):






         """simple docstring"""


         a_	    = FlavaImageProcessingTester(self  )







  @property
  def       _a					( self  ):






         """simple docstring"""


         return self.image_processor_tester.prepare_image_processor_dict()







  def       _a					( self  ):






         """simple docstring"""


         a_	    = self.image_processing_class(**self.image_processor_dict  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'image_mean'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'image_std'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'do_normalize'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'do_resize'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'resample'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'crop_size'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'do_center_crop'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'do_rescale'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'rescale_factor'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'masking_generator'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'codebook_do_resize'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'codebook_size'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'codebook_resample'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'codebook_do_center_crop'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'codebook_crop_size'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'codebook_do_map_pixels'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'codebook_do_normalize'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'codebook_image_mean'  )  )
         self.assertTrue(hasattr(UpperCamelCase__      ,  'codebook_image_std'  )  )







  def       _a					( self  ):






         """simple docstring"""


         a_	    = self.image_processing_class.from_dict(self.image_processor_dict  )
         self.assertEqual(image_processor.size      ,  {'height': 224, 'width': 224}  )
         self.assertEqual(image_processor.crop_size      ,  {'height': 224, 'width': 224}  )
         self.assertEqual(image_processor.codebook_size      ,  {'height': 112, 'width': 112}  )
         self.assertEqual(image_processor.codebook_crop_size      ,  {'height': 112, 'width': 112}  )

         a_	    = self.image_processing_class.from_dict(
             self.image_processor_dict      ,  size=42      ,  crop_size=84      ,  codebook_size=33      ,  codebook_crop_size=66  )
         self.assertEqual(image_processor.size      ,  {'height': 42, 'width': 42}  )
         self.assertEqual(image_processor.crop_size      ,  {'height': 84, 'width': 84}  )
         self.assertEqual(image_processor.codebook_size      ,  {'height': 33, 'width': 33}  )
         self.assertEqual(image_processor.codebook_crop_size      ,  {'height': 66, 'width': 66}  )







  def       _a					( self  ):






         """simple docstring"""


         pass







  def       _a					( self  ):






         """simple docstring"""


         a_	    = self.image_processing_class(**self.image_processor_dict  )
         # create random PIL images
         a_	    = prepare_image_inputs(self.image_processor_tester      ,  equal_resolution=UpperCamelCase__  )
         for image in image_inputs:
                self.assertIsInstance(UpperCamelCase__      ,  PIL.Image.Image  )

         # Test not batched input
         a_	    = image_processing(image_inputs[0]      ,  return_tensors='pt'  )

         # Test no bool masked pos
         self.assertFalse('bool_masked_pos' in encoded_images  )

         a_    ,  a_	    = self.image_processor_tester.get_expected_image_size()

         self.assertEqual(
             encoded_images.pixel_values.shape      ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)      ,  )

         # Test batched
         a_	    = image_processing(UpperCamelCase__      ,  return_tensors='pt'  )
         a_    ,  a_	    = self.image_processor_tester.get_expected_image_size()

         # Test no bool masked pos
         self.assertFalse('bool_masked_pos' in encoded_images  )

         self.assertEqual(
             encoded_images.pixel_values.shape      ,  (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )      ,  )







  def       _a					( self      ,  UpperCamelCase__      ,  UpperCamelCase__  ):






         """simple docstring"""


         a_	    = self.image_processing_class(**self.image_processor_dict  )
         # create random tensors
         a_	    = prepare_image_inputs(self.image_processor_tester      ,  equal_resolution=UpperCamelCase__      ,  **UpperCamelCase__  )
         for image in image_inputs:
                self.assertIsInstance(UpperCamelCase__      ,  UpperCamelCase__  )

         # Test not batched input
         a_	    = image_processing(image_inputs[0]      ,  return_tensors='pt'  )

         a_    ,  a_	    = self.image_processor_tester.get_expected_image_size()
         self.assertEqual(
             encoded_images.pixel_values.shape      ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)      ,  )

         a_	    = image_processing(UpperCamelCase__      ,  return_image_mask=UpperCamelCase__      ,  return_tensors='pt'  )

         a_    ,  a_	    = self.image_processor_tester.get_expected_image_size()
         self.assertEqual(
             encoded_images.pixel_values.shape      ,  (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )      ,  )

         a_    ,  a_	    = self.image_processor_tester.get_expected_mask_size()
         self.assertEqual(
             encoded_images.bool_masked_pos.shape      ,  (
                 self.image_processor_tester.batch_size,
                 expected_height,
                 expected_width,
             )      ,  )

         # Test batched
         a_	    = image_processing(UpperCamelCase__      ,  return_tensors='pt'  ).pixel_values

         a_    ,  a_	    = self.image_processor_tester.get_expected_image_size()
         self.assertEqual(
             encoded_images.shape      ,  (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )      ,  )

         # Test masking
         a_	    = image_processing(UpperCamelCase__      ,  return_image_mask=UpperCamelCase__      ,  return_tensors='pt'  )

         a_    ,  a_	    = self.image_processor_tester.get_expected_image_size()
         self.assertEqual(
             encoded_images.pixel_values.shape      ,  (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )      ,  )

         a_    ,  a_	    = self.image_processor_tester.get_expected_mask_size()
         self.assertEqual(
             encoded_images.bool_masked_pos.shape      ,  (
                 self.image_processor_tester.batch_size,
                 expected_height,
                 expected_width,
             )      ,  )







  def       _a					( self  ):






         """simple docstring"""


         self._test_call_framework(np.ndarray      ,  prepare_kwargs={'numpify': True}  )







  def       _a					( self  ):






         """simple docstring"""


         self._test_call_framework(torch.Tensor      ,  prepare_kwargs={'torchify': True}  )







  def       _a					( self  ):






         """simple docstring"""


         random.seed(1_234  )
         a_	    = self.image_processing_class(**self.image_processor_dict  )
         a_	    = prepare_image_inputs(self.image_processor_tester      ,  equal_resolution=UpperCamelCase__      ,  torchify=UpperCamelCase__  )

         # Test not batched input
         a_	    = image_processing(image_inputs[0]      ,  return_image_mask=UpperCamelCase__      ,  return_tensors='pt'  )
         self.assertEqual(encoded_images.bool_masked_pos.sum().item()      ,  75  )







  def       _a					( self  ):






         """simple docstring"""


         a_	    = self.image_processing_class(**self.image_processor_dict  )
         # create random PIL images
         a_	    = prepare_image_inputs(self.image_processor_tester      ,  equal_resolution=UpperCamelCase__  )
         for image in image_inputs:
                self.assertIsInstance(UpperCamelCase__      ,  PIL.Image.Image  )

         # Test not batched input
         a_	    = image_processing(image_inputs[0]      ,  return_codebook_pixels=UpperCamelCase__      ,  return_tensors='pt'  )
         a_    ,  a_	    = self.image_processor_tester.get_expected_codebook_image_size()
         self.assertEqual(
             encoded_images.codebook_pixel_values.shape      ,  (1, self.image_processor_tester.num_channels, expected_height, expected_width)      ,  )

         # Test batched
         a_	    = image_processing(UpperCamelCase__      ,  return_codebook_pixels=UpperCamelCase__      ,  return_tensors='pt'  )
         a_    ,  a_	    = self.image_processor_tester.get_expected_codebook_image_size()
         self.assertEqual(
             encoded_images.codebook_pixel_values.shape      ,  (
                 self.image_processor_tester.batch_size,
                 self.image_processor_tester.num_channels,
                 expected_height,
                 expected_width,
             )      ,  )




