
"""simple docstring"""

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

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


SCREAMING_SNAKE_CASE_            =    logging.getLogger(__name__)




def      lowercase__    (       lowerCAmelCase					:       List[str]			,					lowerCAmelCase					:       Dict			)			->   Optional[int]:






    """simple docstring"""




    return (preds == labels).mean()
@dataclass
class   _UpperCAmelCase				:
      __SCREAMING_SNAKE_CASE :				str				   =						field(
          metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}				)
      __SCREAMING_SNAKE_CASE :				Optional[str]				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "Pretrained config name or path if not the same as model_name"}				)
      __SCREAMING_SNAKE_CASE :				Optional[str]				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}				)
      __SCREAMING_SNAKE_CASE :				Optional[str]				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}  ,      )

@dataclass
class   _UpperCAmelCase				:
      __SCREAMING_SNAKE_CASE :				str				   =						field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys()				)}				)
      __SCREAMING_SNAKE_CASE :				str				   =						field(metadata={"help": "Should contain the data files for the task."}				)
      __SCREAMING_SNAKE_CASE :				int				   =						field(
          default=1_2_8  ,      metadata={
              "help": (
                  "The maximum total input sequence length after tokenization. Sequences longer "
                  "than this will be truncated, sequences shorter will be padded."
              )
          }  ,      )
      __SCREAMING_SNAKE_CASE :				bool				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "Overwrite the cached training and evaluation sets"}				)




def      lowercase__    (       )			->   int:






    """simple docstring"""




    UpperCAmelCase          =       HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)
    UpperCAmelCase      ,				UpperCAmelCase      ,				UpperCAmelCase          =       parser.parse_args_into_dataclasses()

    if (
        os.path.exists(training_args.output_dir			)
        and os.listdir(training_args.output_dir			)
        and training_args.do_train
        and not training_args.overwrite_output_dir
    ):
        raise ValueError(
            F"Output directory ({training_args.output_dir}) already exists and is not empty. Use"
            ' --overwrite_output_dir to overcome.'			)

    # Setup logging
    logging.basicConfig(
        format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'			,					datefmt='%m/%d/%Y %H:%M:%S'			,					level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN			,					)
    logger.warning(
        'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'			,					training_args.local_rank			,					training_args.device			,					training_args.n_gpu			,					bool(training_args.local_rank != -1			)			,					training_args.fpaa			,					)
    # Set the verbosity to info of the Transformers logger (on main process only):
    if is_main_process(training_args.local_rank			):
        transformers.utils.logging.set_verbosity_info()
        transformers.utils.logging.enable_default_handler()
        transformers.utils.logging.enable_explicit_format()
    logger.info('Training/evaluation parameters %s'			,					lowerCAmelCase			)

    # Set seed
    set_seed(training_args.seed			)

    try:
        UpperCAmelCase          =       processors[data_args.task_name]()
        UpperCAmelCase          =       processor.get_labels()
        UpperCAmelCase          =       len(lowerCAmelCase			)
    except KeyError:
        raise ValueError('Task not found: %s' % (data_args.task_name)			)

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.

    UpperCAmelCase          =       AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path			,					num_labels=lowerCAmelCase			,					finetuning_task=data_args.task_name			,					cache_dir=model_args.cache_dir			,					)
    UpperCAmelCase          =       AutoTokenizer.from_pretrained(
        model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path			,					cache_dir=model_args.cache_dir			,					)
    UpperCAmelCase          =       AutoModelForMultipleChoice.from_pretrained(
        model_args.model_name_or_path			,					from_tf=bool('.ckpt' in model_args.model_name_or_path			)			,					config=lowerCAmelCase			,					cache_dir=model_args.cache_dir			,					)

    # Get datasets
    UpperCAmelCase          =       (
        MultipleChoiceDataset(
            data_dir=data_args.data_dir			,					tokenizer=lowerCAmelCase			,					task=data_args.task_name			,					max_seq_length=data_args.max_seq_length			,					overwrite_cache=data_args.overwrite_cache			,					mode=Split.train			,					)
        if training_args.do_train
        else None
    )
    UpperCAmelCase          =       (
        MultipleChoiceDataset(
            data_dir=data_args.data_dir			,					tokenizer=lowerCAmelCase			,					task=data_args.task_name			,					max_seq_length=data_args.max_seq_length			,					overwrite_cache=data_args.overwrite_cache			,					mode=Split.dev			,					)
        if training_args.do_eval
        else None
    )

    def compute_metrics(lowerCAmelCase					:       EvalPrediction			) -> Dict:
        UpperCAmelCase          =       np.argmax(p.predictions			,					axis=1			)
        return {"acc": simple_accuracy(lowerCAmelCase			,					p.label_ids			)}

    # Data collator
    UpperCAmelCase          =       DataCollatorWithPadding(lowerCAmelCase			,					pad_to_multiple_of=8			) if training_args.fpaa else None

    # Initialize our Trainer
    UpperCAmelCase          =       Trainer(
        model=lowerCAmelCase			,					args=lowerCAmelCase			,					train_dataset=lowerCAmelCase			,					eval_dataset=lowerCAmelCase			,					compute_metrics=lowerCAmelCase			,					data_collator=lowerCAmelCase			,					)

    # Training
    if training_args.do_train:
        trainer.train(
            model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path			) else None			)
        trainer.save_model()
        # For convenience, we also re-save the tokenizer to the same directory,
        # so that you can share your model easily on huggingface.co/models =)
        if trainer.is_world_master():
            tokenizer.save_pretrained(training_args.output_dir			)

    # Evaluation
    UpperCAmelCase          =       {}
    if training_args.do_eval:
        logger.info('*** Evaluate ***'			)

        UpperCAmelCase          =       trainer.evaluate()

        UpperCAmelCase          =       os.path.join(training_args.output_dir			,					'eval_results.txt'			)
        if trainer.is_world_master():
            with open(lowerCAmelCase			,					'w'			) as writer:
                logger.info('***** Eval results *****'			)
                for key, value in result.items():
                    logger.info('  %s = %s'			,					lowerCAmelCase			,					lowerCAmelCase			)
                    writer.write('%s = %s\n' % (key, value)			)

                results.update(lowerCAmelCase			)

    return results




def      lowercase__    (       lowerCAmelCase					:       List[str]			)			->   Union[str, Any]:






    """simple docstring"""




    main()


if __name__ == "__main__":
   main()





"""simple docstring"""

import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
   from transformers import WhisperFeatureExtractor

if is_torch_available():
   import torch

SCREAMING_SNAKE_CASE_            =    random.Random()




def      lowercase__    (       lowerCAmelCase					:       int			,					lowerCAmelCase					:       Union[str, Any]=1.0			,					lowerCAmelCase					:       Any=None			,					lowerCAmelCase					:       Optional[Any]=None			)			->   Dict:






    """simple docstring"""




    if rng is None:
        UpperCAmelCase          =       global_rng

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

    return values
@require_torch
@require_torchaudio
class   _UpperCAmelCase				(		unittest.TestCase				):




      def __init__(				self ,							lowercase_ ,							lowercase_=7 ,							lowercase_=4_0_0 ,							lowercase_=2_0_0_0 ,							lowercase_=1_0 ,							lowercase_=1_6_0 ,							lowercase_=8 ,							lowercase_=0.0 ,							lowercase_=4_0_0_0 ,							lowercase_=False ,							lowercase_=True ,							)    ->       Optional[int]:
          UpperCAmelCase          =       parent
          UpperCAmelCase          =       batch_size
          UpperCAmelCase          =       min_seq_length
          UpperCAmelCase          =       max_seq_length
          UpperCAmelCase          =       (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
          UpperCAmelCase          =       padding_value
          UpperCAmelCase          =       sampling_rate
          UpperCAmelCase          =       return_attention_mask
          UpperCAmelCase          =       do_normalize
          UpperCAmelCase          =       feature_size
          UpperCAmelCase          =       chunk_length
          UpperCAmelCase          =       hop_length




      def      a_   (				self				)    ->       Dict:
          return {
              "feature_size": self.feature_size,
              "hop_length": self.hop_length,
              "chunk_length": self.chunk_length,
              "padding_value": self.padding_value,
              "sampling_rate": self.sampling_rate,
              "return_attention_mask": self.return_attention_mask,
              "do_normalize": self.do_normalize,
          }




      def      a_   (				self ,							lowercase_=False ,							lowercase_=False				)    ->       Optional[Any]:
          def _flatten(lowercase_				):
              return list(itertools.chain(*lowercase_				)				)

          if equal_length:
              UpperCAmelCase          =       [floats_list((self.max_seq_length, self.feature_size)				) for _ in range(self.batch_size				)]
          else:
              # make sure that inputs increase in size
              UpperCAmelCase          =       [
                  floats_list((x, self.feature_size)				)
                  for x in range(self.min_seq_length ,							self.max_seq_length ,							self.seq_length_diff				)
              ]
          if numpify:
              UpperCAmelCase          =       [np.asarray(lowercase_				) for x in speech_inputs]
          return speech_inputs

@require_torch
@require_torchaudio
class   _UpperCAmelCase				(		SCREAMING_SNAKE_CASE_  ,      unittest.TestCase				):
      __SCREAMING_SNAKE_CASE :				List[Any]				   =						WhisperFeatureExtractor if is_speech_available() else None




      def      a_   (				self				)    ->       Union[str, Any]:
          UpperCAmelCase          =       WhisperFeatureExtractionTester(self				)




      def      a_   (				self				)    ->       List[str]:
          UpperCAmelCase          =       self.feature_extraction_class(**self.feat_extract_dict				)

          with tempfile.TemporaryDirectory() as tmpdirname:
              UpperCAmelCase          =       feat_extract_first.save_pretrained(lowercase_				)[0]
              check_json_file_has_correct_format(lowercase_				)
              UpperCAmelCase          =       self.feature_extraction_class.from_pretrained(lowercase_				)

          UpperCAmelCase          =       feat_extract_first.to_dict()
          UpperCAmelCase          =       feat_extract_second.to_dict()
          UpperCAmelCase          =       feat_extract_first.mel_filters
          UpperCAmelCase          =       feat_extract_second.mel_filters
          self.assertTrue(np.allclose(lowercase_ ,							lowercase_				)				)
          self.assertEqual(lowercase_ ,							lowercase_				)




      def      a_   (				self				)    ->       List[str]:
          UpperCAmelCase          =       self.feature_extraction_class(**self.feat_extract_dict				)

          with tempfile.TemporaryDirectory() as tmpdirname:
              UpperCAmelCase          =       os.path.join(lowercase_ ,							'feat_extract.json'				)
              feat_extract_first.to_json_file(lowercase_				)
              UpperCAmelCase          =       self.feature_extraction_class.from_json_file(lowercase_				)

          UpperCAmelCase          =       feat_extract_first.to_dict()
          UpperCAmelCase          =       feat_extract_second.to_dict()
          UpperCAmelCase          =       feat_extract_first.mel_filters
          UpperCAmelCase          =       feat_extract_second.mel_filters
          self.assertTrue(np.allclose(lowercase_ ,							lowercase_				)				)
          self.assertEqual(lowercase_ ,							lowercase_				)




      def      a_   (				self				)    ->       Tuple:
          # Tests that all call wrap to encode_plus and batch_encode_plus
          UpperCAmelCase          =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
          # create three inputs of length 800, 1000, and 1200
          UpperCAmelCase          =       [floats_list((1, x)				)[0] for x in range(8_0_0 ,							1_4_0_0 ,							2_0_0				)]
          UpperCAmelCase          =       [np.asarray(lowercase_				) for speech_input in speech_inputs]

          # Test feature size
          UpperCAmelCase          =       feature_extractor(lowercase_ ,							padding='max_length' ,							return_tensors='np'				).input_features
          self.assertTrue(input_features.ndim == 3				)
          self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames				)
          self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size				)

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

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

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

          # Test truncation required
          UpperCAmelCase          =       [floats_list((1, x)				)[0] for x in range(2_0_0 ,							(feature_extractor.n_samples + 5_0_0) ,							2_0_0				)]
          UpperCAmelCase          =       [np.asarray(lowercase_				) for speech_input in speech_inputs]

          UpperCAmelCase          =       [x[: feature_extractor.n_samples] for x in speech_inputs]
          UpperCAmelCase          =       [np.asarray(lowercase_				) for speech_input in speech_inputs_truncated]

          UpperCAmelCase          =       feature_extractor(lowercase_ ,							return_tensors='np'				).input_features
          UpperCAmelCase          =       feature_extractor(lowercase_ ,							return_tensors='np'				).input_features
          for enc_seq_a, enc_seq_a in zip(lowercase_ ,							lowercase_				):
              self.assertTrue(np.allclose(lowercase_ ,							lowercase_ ,							atol=1E-3				)				)




      def      a_   (				self				)    ->       List[Any]:
          import torch

          UpperCAmelCase          =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
          UpperCAmelCase          =       np.random.rand(1_0_0 ,							3_2				).astype(np.floataa				)
          UpperCAmelCase          =       np_speech_inputs.tolist()

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




      def      a_   (				self ,							lowercase_				)    ->       Optional[Any]:
          UpperCAmelCase          =       load_dataset('hf-internal-testing/librispeech_asr_dummy' ,							'clean' ,							split='validation'				)
          # automatic decoding with librispeech
          UpperCAmelCase          =       ds.sort('id'				).select(range(lowercase_				)				)[:num_samples]['audio']

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




      def      a_   (				self				)    ->       Dict:
          # fmt: off
          UpperCAmelCase          =       torch.tensor(
              [
                  0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
                  0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
                  0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
                  -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
              ]				)
          # fmt: on

          UpperCAmelCase          =       self._load_datasamples(1				)
          UpperCAmelCase          =       WhisperFeatureExtractor()
          UpperCAmelCase          =       feature_extractor(lowercase_ ,							return_tensors='pt'				).input_features
          self.assertEqual(input_features.shape ,							(1, 8_0, 3_0_0_0)				)
          self.assertTrue(torch.allclose(input_features[0, 0, :3_0] ,							lowercase_ ,							atol=1E-4				)				)




      def      a_   (				self				)    ->       Optional[Any]:
          UpperCAmelCase          =       self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()				)
          UpperCAmelCase          =       self._load_datasamples(1				)[0]
          UpperCAmelCase          =       ((audio - audio.min()) / (audio.max() - audio.min())) * 6_5_5_3_5  # Rescale to [0, 65535] to show issue
          UpperCAmelCase          =       feat_extract.zero_mean_unit_var_norm([audio] ,							attention_mask=lowercase_				)[0]

          self.assertTrue(np.all(np.mean(lowercase_				) < 1E-3				)				)
          self.assertTrue(np.all(np.abs(np.var(lowercase_				) - 1				) < 1E-3				)				)



