




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
lowerCamelCase__					:  str      							=				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')

lowerCamelCase__					:  Optional[int]      							=				list(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING.keys())
lowerCamelCase__					:  str      							=				tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

def    UpperCAmelCase_				( __UpperCAmelCase		:      str				)   ->					Optional[Any]:
      with open(__UpperCAmelCase     ,     'rb'				) as f:
            SCREAMING_SNAKE_CASE_      		=     Image.open(__UpperCAmelCase				)
            return im.convert('RGB'				)





@dataclass
class 			lowerCamelCase_				:


 '''simple docstring'''







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



 def  lowerCAmelCase_    (				self    :						List[Any]		):
       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 			lowerCamelCase_				:


 '''simple docstring'''







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


def    UpperCAmelCase_				( __UpperCAmelCase		:      Optional[int]				)   ->					List[str]:
      SCREAMING_SNAKE_CASE_      		=     torch.stack([example['pixel_values'] for example in examples]				)
      SCREAMING_SNAKE_CASE_      		=     torch.tensor([example['labels'] for example in examples]				)
      return {"pixel_values": pixel_values, "labels": labels}

def    UpperCAmelCase_				( )   ->					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.

      SCREAMING_SNAKE_CASE_      		=     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.
            SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
      else:
            SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     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()

      SCREAMING_SNAKE_CASE_      		=     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.
      SCREAMING_SNAKE_CASE_      		=     None
      if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
            SCREAMING_SNAKE_CASE_      		=     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:
            SCREAMING_SNAKE_CASE_      		=     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:
            SCREAMING_SNAKE_CASE_      		=     {}
            if data_args.train_dir is not None:
                  SCREAMING_SNAKE_CASE_      		=     os.path.join(data_args.train_dir     ,     '**'				)
            if data_args.validation_dir is not None:
                  SCREAMING_SNAKE_CASE_      		=     os.path.join(data_args.validation_dir     ,     '**'				)
            SCREAMING_SNAKE_CASE_      		=     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.
      SCREAMING_SNAKE_CASE_      		=     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:
            SCREAMING_SNAKE_CASE_      		=     dataset['train'].train_test_split(data_args.train_val_split				)
            SCREAMING_SNAKE_CASE_      		=     split['train']
            SCREAMING_SNAKE_CASE_      		=     split['test']

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

      # Load the accuracy metric from the datasets package
      SCREAMING_SNAKE_CASE_      		=     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(__UpperCAmelCase		:      Any				):
            return metric.compute(predictions=np.argmax(p.predictions     ,     axis=1				)     ,     references=p.label_ids				)

      SCREAMING_SNAKE_CASE_      		=     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     ,     )
      SCREAMING_SNAKE_CASE_      		=     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     ,     )
      SCREAMING_SNAKE_CASE_      		=     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:
            SCREAMING_SNAKE_CASE_      		=     image_processor.size['shortest_edge']
      else:
            SCREAMING_SNAKE_CASE_      		=     (image_processor.size['height'], image_processor.size['width'])
      SCREAMING_SNAKE_CASE_      		=     Normalize(mean=image_processor.image_mean     ,     std=image_processor.image_std				)
      SCREAMING_SNAKE_CASE_      		=     Compose(
          [
              RandomResizedCrop(__UpperCAmelCase				),
              RandomHorizontalFlip(),
              ToTensor(),
              normalize,
          ]				)
      SCREAMING_SNAKE_CASE_      		=     Compose(
          [
              Resize(__UpperCAmelCase				),
              CenterCrop(__UpperCAmelCase				),
              ToTensor(),
              normalize,
          ]				)

      def train_transforms(__UpperCAmelCase		:      Dict				):
            SCREAMING_SNAKE_CASE_      		=     [
                _train_transforms(pil_img.convert('RGB'				)				) for pil_img in example_batch['image']
            ]
            return example_batch

      def val_transforms(__UpperCAmelCase		:      Any				):
            SCREAMING_SNAKE_CASE_      		=     [_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:
                  SCREAMING_SNAKE_CASE_      		=     (
                      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:
                  SCREAMING_SNAKE_CASE_      		=     (
                      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
      SCREAMING_SNAKE_CASE_      		=     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:
            SCREAMING_SNAKE_CASE_      		=     None
            if training_args.resume_from_checkpoint is not None:
                  SCREAMING_SNAKE_CASE_      		=     training_args.resume_from_checkpoint
            elif last_checkpoint is not None:
                  SCREAMING_SNAKE_CASE_      		=     last_checkpoint
            SCREAMING_SNAKE_CASE_      		=     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:
            SCREAMING_SNAKE_CASE_      		=     trainer.evaluate()
            trainer.log_metrics('eval'     ,     __UpperCAmelCase				)
            trainer.save_metrics('eval'     ,     __UpperCAmelCase				)

      # Write model card and (optionally) push to hub
      SCREAMING_SNAKE_CASE_      		=     {
          '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()





import itertools
import random
import unittest

import numpy as np

from transformers import BatchFeature, SpeechTaFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
   import torch


lowerCamelCase__					:  Dict      							=				random.Random()

def    UpperCAmelCase_				( __UpperCAmelCase		:      int     ,     __UpperCAmelCase		:      Tuple=1.0     ,     __UpperCAmelCase		:      Dict=None     ,     __UpperCAmelCase		:      Dict=None				)   ->					Tuple:
      if rng is None:
            SCREAMING_SNAKE_CASE_      		=     global_rng

      SCREAMING_SNAKE_CASE_      		=     []
      for batch_idx in range(shape[0]				):
            values.append([]				)
            for _ in range(shape[1]				):
                  values[-1].append(rng.random() * scale				)

      return values





@require_torch
class 			lowerCamelCase_				( unittest.TestCase   ):


 '''simple docstring'''







 def __init__(				self    :						List[str]							,							_lowerCAmelCase    :						int							,							_lowerCAmelCase    :						Optional[Any]=7							,							_lowerCAmelCase    :						Union[str, Any]=400							,							_lowerCAmelCase    :						Tuple=2_000							,							_lowerCAmelCase    :						str=1							,							_lowerCAmelCase    :						int=0.0							,							_lowerCAmelCase    :						Optional[Any]=16_000							,							_lowerCAmelCase    :						Optional[Any]=True							,							_lowerCAmelCase    :						Any=80							,							_lowerCAmelCase    :						Union[str, Any]=16							,							_lowerCAmelCase    :						List[str]=64							,							_lowerCAmelCase    :						List[Any]="hann_window"							,							_lowerCAmelCase    :						Any=80							,							_lowerCAmelCase    :						List[Any]=7_600							,							_lowerCAmelCase    :						List[Any]=1E-10							,							_lowerCAmelCase    :						Optional[Any]=True							,							):
       SCREAMING_SNAKE_CASE_      		=     parent
       SCREAMING_SNAKE_CASE_      		=     batch_size
       SCREAMING_SNAKE_CASE_      		=     min_seq_length
       SCREAMING_SNAKE_CASE_      		=     max_seq_length
       SCREAMING_SNAKE_CASE_      		=     (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
       SCREAMING_SNAKE_CASE_      		=     feature_size
       SCREAMING_SNAKE_CASE_      		=     padding_value
       SCREAMING_SNAKE_CASE_      		=     sampling_rate
       SCREAMING_SNAKE_CASE_      		=     do_normalize
       SCREAMING_SNAKE_CASE_      		=     num_mel_bins
       SCREAMING_SNAKE_CASE_      		=     hop_length
       SCREAMING_SNAKE_CASE_      		=     win_length
       SCREAMING_SNAKE_CASE_      		=     win_function
       SCREAMING_SNAKE_CASE_      		=     fmin
       SCREAMING_SNAKE_CASE_      		=     fmax
       SCREAMING_SNAKE_CASE_      		=     mel_floor
       SCREAMING_SNAKE_CASE_      		=     return_attention_mask



 def  lowerCAmelCase_    (				self    :						Union[str, Any]		):
       return {
           "feature_size": self.feature_size,
           "padding_value": self.padding_value,
           "sampling_rate": self.sampling_rate,
           "do_normalize": self.do_normalize,
           "num_mel_bins": self.num_mel_bins,
           "hop_length": self.hop_length,
           "win_length": self.win_length,
           "win_function": self.win_function,
           "fmin": self.fmin,
           "fmax": self.fmax,
           "mel_floor": self.mel_floor,
           "return_attention_mask": self.return_attention_mask,
       }



 def  lowerCAmelCase_    (				self    :						Dict							,							_lowerCAmelCase    :						Optional[int]=False							,							_lowerCAmelCase    :						str=False		):
       def _flatten(_lowerCAmelCase    :						Dict		):
             return list(itertools.chain(*_lowerCAmelCase		)		)

       if equal_length:
             SCREAMING_SNAKE_CASE_      		=     floats_list((self.batch_size, self.max_seq_length)		)
       else:
             # make sure that inputs increase in size
             SCREAMING_SNAKE_CASE_      		=     [
                 _flatten(floats_list((x, self.feature_size)		)		)
                 for x in range(self.min_seq_length							,							self.max_seq_length							,							self.seq_length_diff		)
             ]

       if numpify:
             SCREAMING_SNAKE_CASE_      		=     [np.asarray(_lowerCAmelCase		) for x in speech_inputs]

       return speech_inputs




 def  lowerCAmelCase_    (				self    :						List[Any]							,							_lowerCAmelCase    :						Union[str, Any]=False							,							_lowerCAmelCase    :						Optional[int]=False		):
       if equal_length:
             SCREAMING_SNAKE_CASE_      		=     [floats_list((self.max_seq_length, self.num_mel_bins)		) for _ in range(self.batch_size		)]
       else:
             # make sure that inputs increase in size
             SCREAMING_SNAKE_CASE_      		=     [
                 floats_list((x, self.num_mel_bins)		)
                 for x in range(self.min_seq_length							,							self.max_seq_length							,							self.seq_length_diff		)
             ]

       if numpify:
             SCREAMING_SNAKE_CASE_      		=     [np.asarray(_lowerCAmelCase		) for x in speech_inputs]

       return speech_inputs





@require_torch
class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE			,  unittest.TestCase   ):


 '''simple docstring'''







 lowercase_							       =       SpeechTaFeatureExtractor



 def  lowerCAmelCase_    (				self    :						Any		):
       SCREAMING_SNAKE_CASE_      		=     SpeechTaFeatureExtractionTester(self		)



 def  lowerCAmelCase_    (				self    :						Any							,							_lowerCAmelCase    :						int		):
       self.assertTrue(np.all(np.mean(_lowerCAmelCase							,							axis=0		) < 1E-3		)		)
       self.assertTrue(np.all(np.abs(np.var(_lowerCAmelCase							,							axis=0		) - 1		) < 1E-3		)		)



 def  lowerCAmelCase_    (				self    :						List[Any]		):
       # Tests that all call wrap to encode_plus and batch_encode_plus
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
       # create three inputs of length 800, 1000, and 1200
       SCREAMING_SNAKE_CASE_      		=     [floats_list((1, x)		)[0] for x in range(800							,							1_400							,							200		)]
       SCREAMING_SNAKE_CASE_      		=     [np.asarray(_lowerCAmelCase		) for speech_input in speech_inputs]

       # Test not batched input
       SCREAMING_SNAKE_CASE_      		=     feat_extract(speech_inputs[0]							,							return_tensors='np'		).input_values
       SCREAMING_SNAKE_CASE_      		=     feat_extract(np_speech_inputs[0]							,							return_tensors='np'		).input_values
       self.assertTrue(np.allclose(_lowerCAmelCase							,							_lowerCAmelCase							,							atol=1E-3		)		)

       # Test batched
       SCREAMING_SNAKE_CASE_      		=     feat_extract(_lowerCAmelCase							,							return_tensors='np'		).input_values
       SCREAMING_SNAKE_CASE_      		=     feat_extract(_lowerCAmelCase							,							return_tensors='np'		).input_values
       for enc_seq_a, enc_seq_a in zip(_lowerCAmelCase							,							_lowerCAmelCase		):
             self.assertTrue(np.allclose(_lowerCAmelCase							,							_lowerCAmelCase							,							atol=1E-3		)		)



 def  lowerCAmelCase_    (				self    :						Union[str, Any]		):
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
       SCREAMING_SNAKE_CASE_      		=     [floats_list((1, x)		)[0] for x in range(800							,							1_400							,							200		)]

       SCREAMING_SNAKE_CASE_      		=     ['longest', 'max_length', 'do_not_pad']
       SCREAMING_SNAKE_CASE_      		=     [None, 1_600, None]
       for max_length, padding in zip(_lowerCAmelCase							,							_lowerCAmelCase		):
             SCREAMING_SNAKE_CASE_      		=     feat_extract(_lowerCAmelCase							,							padding=_lowerCAmelCase							,							max_length=_lowerCAmelCase							,							return_tensors='np'		)
             SCREAMING_SNAKE_CASE_      		=     processed.input_values

             self._check_zero_mean_unit_variance(input_values[0][:800]		)
             self.assertTrue(input_values[0][800:].sum() < 1E-6		)
             self._check_zero_mean_unit_variance(input_values[1][:1_000]		)
             self.assertTrue(input_values[0][1_000:].sum() < 1E-6		)
             self._check_zero_mean_unit_variance(input_values[2][:1_200]		)



 def  lowerCAmelCase_    (				self    :						Optional[Any]		):
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
       SCREAMING_SNAKE_CASE_      		=     range(800							,							1_400							,							200		)
       SCREAMING_SNAKE_CASE_      		=     [floats_list((1, x)		)[0] for x in lengths]

       SCREAMING_SNAKE_CASE_      		=     ['longest', 'max_length', 'do_not_pad']
       SCREAMING_SNAKE_CASE_      		=     [None, 1_600, None]

       for max_length, padding in zip(_lowerCAmelCase							,							_lowerCAmelCase		):
             SCREAMING_SNAKE_CASE_      		=     feat_extract(_lowerCAmelCase							,							max_length=_lowerCAmelCase							,							padding=_lowerCAmelCase		)
             SCREAMING_SNAKE_CASE_      		=     processed.input_values

             self._check_zero_mean_unit_variance(input_values[0][:800]		)
             self._check_zero_mean_unit_variance(input_values[1][:1_000]		)
             self._check_zero_mean_unit_variance(input_values[2][:1_200]		)



 def  lowerCAmelCase_    (				self    :						Dict		):
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
       SCREAMING_SNAKE_CASE_      		=     [floats_list((1, x)		)[0] for x in range(800							,							1_400							,							200		)]
       SCREAMING_SNAKE_CASE_      		=     feat_extract(
           _lowerCAmelCase							,							truncation=_lowerCAmelCase							,							max_length=1_000							,							padding='max_length'							,							return_tensors='np'		)
       SCREAMING_SNAKE_CASE_      		=     processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]		)
       self._check_zero_mean_unit_variance(input_values[1]		)
       self._check_zero_mean_unit_variance(input_values[2]		)



 def  lowerCAmelCase_    (				self    :						Dict		):
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
       SCREAMING_SNAKE_CASE_      		=     [floats_list((1, x)		)[0] for x in range(800							,							1_400							,							200		)]
       SCREAMING_SNAKE_CASE_      		=     feat_extract(
           _lowerCAmelCase							,							truncation=_lowerCAmelCase							,							max_length=1_000							,							padding='longest'							,							return_tensors='np'		)
       SCREAMING_SNAKE_CASE_      		=     processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]		)
       self._check_zero_mean_unit_variance(input_values[1, :1_000]		)
       self._check_zero_mean_unit_variance(input_values[2]		)

       # make sure that if max_length < longest -> then pad to max_length
       self.assertTrue(input_values.shape == (3, 1_000)		)

       SCREAMING_SNAKE_CASE_      		=     [floats_list((1, x)		)[0] for x in range(800							,							1_400							,							200		)]
       SCREAMING_SNAKE_CASE_      		=     feat_extract(
           _lowerCAmelCase							,							truncation=_lowerCAmelCase							,							max_length=2_000							,							padding='longest'							,							return_tensors='np'		)
       SCREAMING_SNAKE_CASE_      		=     processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]		)
       self._check_zero_mean_unit_variance(input_values[1, :1_000]		)
       self._check_zero_mean_unit_variance(input_values[2]		)

       # make sure that if max_length > longest -> then pad to longest
       self.assertTrue(input_values.shape == (3, 1_200)		)



 def  lowerCAmelCase_    (				self    :						Optional[int]		):
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
       SCREAMING_SNAKE_CASE_      		=     np.random.rand(100		).astype(np.floataa		)
       SCREAMING_SNAKE_CASE_      		=     np_speech_inputs.tolist()

       for inputs in [py_speech_inputs, np_speech_inputs]:
             SCREAMING_SNAKE_CASE_      		=     feature_extractor.pad([{'input_values': inputs}]							,							return_tensors='np'		)
             self.assertTrue(np_processed.input_values.dtype == np.floataa		)
             SCREAMING_SNAKE_CASE_      		=     feature_extractor.pad([{'input_values': inputs}]							,							return_tensors='pt'		)
             self.assertTrue(pt_processed.input_values.dtype == torch.floataa		)



 def  lowerCAmelCase_    (				self    :						Tuple		):
       # Tests that all call wrap to encode_plus and batch_encode_plus
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()		)
       # create three inputs of length 800, 1000, and 1200
       SCREAMING_SNAKE_CASE_      		=     [floats_list((1, x)		)[0] for x in range(800							,							1_400							,							200		)]
       SCREAMING_SNAKE_CASE_      		=     [np.asarray(_lowerCAmelCase		) for speech_input in speech_inputs]

       # Test feature size
       SCREAMING_SNAKE_CASE_      		=     feature_extractor(audio_target=_lowerCAmelCase							,							padding=_lowerCAmelCase							,							return_tensors='np'		).input_values
       self.assertTrue(input_values.ndim == 3		)
       self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins		)

       # Test not batched input
       SCREAMING_SNAKE_CASE_      		=     feature_extractor(speech_inputs[0]							,							return_tensors='np'		).input_values
       SCREAMING_SNAKE_CASE_      		=     feature_extractor(np_speech_inputs[0]							,							return_tensors='np'		).input_values
       self.assertTrue(np.allclose(_lowerCAmelCase							,							_lowerCAmelCase							,							atol=1E-3		)		)

       # Test batched
       SCREAMING_SNAKE_CASE_      		=     feature_extractor(_lowerCAmelCase							,							return_tensors='np'		).input_values
       SCREAMING_SNAKE_CASE_      		=     feature_extractor(_lowerCAmelCase							,							return_tensors='np'		).input_values
       for enc_seq_a, enc_seq_a in zip(_lowerCAmelCase							,							_lowerCAmelCase		):
             self.assertTrue(np.allclose(_lowerCAmelCase							,							_lowerCAmelCase							,							atol=1E-3		)		)

       # Test 2-D numpy arrays are batched.
       SCREAMING_SNAKE_CASE_      		=     [floats_list((1, x)		)[0] for x in (800, 800, 800)]
       SCREAMING_SNAKE_CASE_      		=     np.asarray(_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     feature_extractor(_lowerCAmelCase							,							return_tensors='np'		).input_values
       SCREAMING_SNAKE_CASE_      		=     feature_extractor(_lowerCAmelCase							,							return_tensors='np'		).input_values
       for enc_seq_a, enc_seq_a in zip(_lowerCAmelCase							,							_lowerCAmelCase		):
             self.assertTrue(np.allclose(_lowerCAmelCase							,							_lowerCAmelCase							,							atol=1E-3		)		)



 def  lowerCAmelCase_    (				self    :						str		):
       SCREAMING_SNAKE_CASE_      		=     self.feat_extract_tester.prepare_inputs_for_target()
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**self.feat_extract_dict		)
       SCREAMING_SNAKE_CASE_      		=     feat_extract.model_input_names[0]

       SCREAMING_SNAKE_CASE_      		=     BatchFeature({input_name: speech_inputs}		)

       self.assertTrue(all(len(_lowerCAmelCase		) == len(_lowerCAmelCase		) for x, y in zip(_lowerCAmelCase							,							processed_features[input_name]		)		)		)

       SCREAMING_SNAKE_CASE_      		=     self.feat_extract_tester.prepare_inputs_for_target(equal_length=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     BatchFeature({input_name: speech_inputs}							,							tensor_type='np'		)

       SCREAMING_SNAKE_CASE_      		=     processed_features[input_name]

       if len(batch_features_input.shape		) < 3:
             SCREAMING_SNAKE_CASE_      		=     batch_features_input[:, :, None]

       self.assertTrue(
           batch_features_input.shape
           == (self.feat_extract_tester.batch_size, len(speech_inputs[0]		), self.feat_extract_tester.num_mel_bins)		)



 @require_torch
 def  lowerCAmelCase_    (				self    :						Dict		):
       SCREAMING_SNAKE_CASE_      		=     self.feat_extract_tester.prepare_inputs_for_target(equal_length=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**self.feat_extract_dict		)
       SCREAMING_SNAKE_CASE_      		=     feat_extract.model_input_names[0]

       SCREAMING_SNAKE_CASE_      		=     BatchFeature({input_name: speech_inputs}							,							tensor_type='pt'		)

       SCREAMING_SNAKE_CASE_      		=     processed_features[input_name]

       if len(batch_features_input.shape		) < 3:
             SCREAMING_SNAKE_CASE_      		=     batch_features_input[:, :, None]

       self.assertTrue(
           batch_features_input.shape
           == (self.feat_extract_tester.batch_size, len(speech_inputs[0]		), self.feat_extract_tester.num_mel_bins)		)



 @require_torch
 def  lowerCAmelCase_    (				self    :						Dict		):
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**self.feat_extract_dict		)
       SCREAMING_SNAKE_CASE_      		=     self.feat_extract_tester.prepare_inputs_for_target()
       SCREAMING_SNAKE_CASE_      		=     feat_extract.model_input_names[0]

       SCREAMING_SNAKE_CASE_      		=     BatchFeature({input_name: speech_inputs}		)

       SCREAMING_SNAKE_CASE_      		=     feat_extract.num_mel_bins  # hack!

       SCREAMING_SNAKE_CASE_      		=     feat_extract.pad(_lowerCAmelCase							,							padding='longest'							,							return_tensors='np'		)[input_name]
       SCREAMING_SNAKE_CASE_      		=     feat_extract.pad(_lowerCAmelCase							,							padding='longest'							,							return_tensors='pt'		)[input_name]

       self.assertTrue(abs(input_np.astype(np.floataa		).sum() - input_pt.numpy().astype(np.floataa		).sum()		) < 1E-2		)



 def  lowerCAmelCase_    (				self    :						str		):
       SCREAMING_SNAKE_CASE_      		=     self.feat_extract_dict
       SCREAMING_SNAKE_CASE_      		=     True
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.feat_extract_tester.prepare_inputs_for_target()
       SCREAMING_SNAKE_CASE_      		=     [len(_lowerCAmelCase		) for x in speech_inputs]
       SCREAMING_SNAKE_CASE_      		=     feat_extract.model_input_names[0]

       SCREAMING_SNAKE_CASE_      		=     BatchFeature({input_name: speech_inputs}		)

       SCREAMING_SNAKE_CASE_      		=     feat_extract.num_mel_bins  # hack!

       SCREAMING_SNAKE_CASE_      		=     feat_extract.pad(_lowerCAmelCase							,							padding='longest'							,							return_tensors='np'		)
       self.assertIn('attention_mask'							,							_lowerCAmelCase		)
       self.assertListEqual(list(processed.attention_mask.shape		)							,							list(processed[input_name].shape[:2]		)		)
       self.assertListEqual(processed.attention_mask.sum(-1		).tolist()							,							_lowerCAmelCase		)



 def  lowerCAmelCase_    (				self    :						Any		):
       SCREAMING_SNAKE_CASE_      		=     self.feat_extract_dict
       SCREAMING_SNAKE_CASE_      		=     True
       SCREAMING_SNAKE_CASE_      		=     self.feature_extraction_class(**_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.feat_extract_tester.prepare_inputs_for_target()
       SCREAMING_SNAKE_CASE_      		=     [len(_lowerCAmelCase		) for x in speech_inputs]
       SCREAMING_SNAKE_CASE_      		=     feat_extract.model_input_names[0]

       SCREAMING_SNAKE_CASE_      		=     BatchFeature({input_name: speech_inputs}		)
       SCREAMING_SNAKE_CASE_      		=     min(_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     feat_extract.num_mel_bins  # hack!

       SCREAMING_SNAKE_CASE_      		=     feat_extract.pad(
           _lowerCAmelCase							,							padding='max_length'							,							max_length=_lowerCAmelCase							,							truncation=_lowerCAmelCase							,							return_tensors='np'		)
       self.assertIn('attention_mask'							,							_lowerCAmelCase		)
       self.assertListEqual(
           list(processed_pad.attention_mask.shape		)							,							[processed_pad[input_name].shape[0], max_length]		)
       self.assertListEqual(
           processed_pad.attention_mask[:, :max_length].sum(-1		).tolist()							,							[max_length for x in speech_inputs]		)



 def  lowerCAmelCase_    (				self    :						List[Any]							,							_lowerCAmelCase    :						Tuple		):
       from datasets import load_dataset

       SCREAMING_SNAKE_CASE_      		=     load_dataset('hf-internal-testing/librispeech_asr_dummy'							,							'clean'							,							split='validation'		)
       # automatic decoding with librispeech
       SCREAMING_SNAKE_CASE_      		=     ds.sort('id'		).select(range(_lowerCAmelCase		)		)[:num_samples]['audio']

       return [x["array"] for x in speech_samples]



 def  lowerCAmelCase_    (				self    :						Any		):
       # fmt: off
       SCREAMING_SNAKE_CASE_      		=     torch.tensor(
           [2.3_804E-03, 2.0_752E-03, 1.9_836E-03, 2.1_057E-03, 1.6_174E-03,
            3.0_518E-04, 9.1_553E-05, 3.3_569E-04, 9.7_656E-04, 1.8_311E-03,
            2.0_142E-03, 2.1_057E-03, 1.7_395E-03, 4.5_776E-04, -3.9_673E-04,
            4.5_776E-04, 1.0_071E-03, 9.1_553E-05, 4.8_828E-04, 1.1_597E-03,
            7.3_242E-04, 9.4_604E-04, 1.8_005E-03, 1.8_311E-03, 8.8_501E-04,
            4.2_725E-04, 4.8_828E-04, 7.3_242E-04, 1.0_986E-03, 2.1_057E-03]		)
       # fmt: on

       SCREAMING_SNAKE_CASE_      		=     self._load_datasamples(1		)
       SCREAMING_SNAKE_CASE_      		=     SpeechTaFeatureExtractor()
       SCREAMING_SNAKE_CASE_      		=     feature_extractor(_lowerCAmelCase							,							return_tensors='pt'		).input_values
       self.assertEquals(input_values.shape							,							(1, 93_680)		)
       self.assertTrue(torch.allclose(input_values[0, :30]							,							_lowerCAmelCase							,							atol=1E-6		)		)




 def  lowerCAmelCase_    (				self    :						Optional[int]		):
       # fmt: off
       SCREAMING_SNAKE_CASE_      		=     torch.tensor(
           [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777,
            -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386,
            -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571,
            -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998]		)
       # fmt: on

       SCREAMING_SNAKE_CASE_      		=     self._load_datasamples(1		)
       SCREAMING_SNAKE_CASE_      		=     SpeechTaFeatureExtractor()
       SCREAMING_SNAKE_CASE_      		=     feature_extractor(audio_target=_lowerCAmelCase							,							return_tensors='pt'		).input_values
       self.assertEquals(input_values.shape							,							(1, 366, 80)		)
       self.assertTrue(torch.allclose(input_values[0, 0, :30]							,							_lowerCAmelCase							,							atol=1E-4		)		)