
"""simple docstring"""

import io
import itertools
import json
from dataclasses import dataclass
from typing import Optional

import pyarrow as pa
import pyarrow.json as paj

import datasets
from datasets.table import table_cast
from datasets.utils.file_utils import readline


SCREAMING_SNAKE_CASE_            =    datasets.utils.logging.get_logger(__name__)
@dataclass
class   _UpperCAmelCase				(		datasets.BuilderConfig				):
      __SCREAMING_SNAKE_CASE :				Optional[datasets.Features]				   =						None
      __SCREAMING_SNAKE_CASE :				str				   =						"utf-8"
      __SCREAMING_SNAKE_CASE :				Optional[str]				   =						None
      __SCREAMING_SNAKE_CASE :				Optional[str]				   =						None
      __SCREAMING_SNAKE_CASE :				bool				   =						True  # deprecated
      __SCREAMING_SNAKE_CASE :				Optional[int]				   =						None  # deprecated
      __SCREAMING_SNAKE_CASE :				int				   =						1_0 << 2_0  # 10MB
      __SCREAMING_SNAKE_CASE :				Optional[bool]				   =						None

class   _UpperCAmelCase				(		datasets.ArrowBasedBuilder				):
      __SCREAMING_SNAKE_CASE :				Optional[int]				   =						JsonConfig




      def      a_   (				self				)    ->       List[str]:
          if self.config.block_size is not None:
              logger.warning('The JSON loader parameter `block_size` is deprecated. Please use `chunksize` instead'				)
              UpperCAmelCase          =       self.config.block_size
          if self.config.use_threads is not True:
              logger.warning(
                  'The JSON loader parameter `use_threads` is deprecated and doesn\'t have any effect anymore.'				)
          if self.config.newlines_in_values is not None:
              raise ValueError('The JSON loader parameter `newlines_in_values` is no longer supported'				)
          return datasets.DatasetInfo(features=self.config.features				)




      def      a_   (				self ,							lowercase_				)    ->       Optional[int]:
          if not self.config.data_files:
              raise ValueError(F"At least one data file must be specified, but got data_files={self.config.data_files}"				)
          UpperCAmelCase          =       dl_manager.download_and_extract(self.config.data_files				)
          if isinstance(lowercase_ ,							(str, list, tuple)				):
              UpperCAmelCase          =       data_files
              if isinstance(lowercase_ ,							lowercase_				):
                  UpperCAmelCase          =       [files]
              UpperCAmelCase          =       [dl_manager.iter_files(lowercase_				) for file in files]
              return [datasets.SplitGenerator(name=datasets.Split.TRAIN ,							gen_kwargs={'files': files}				)]
          UpperCAmelCase          =       []
          for split_name, files in data_files.items():
              if isinstance(lowercase_ ,							lowercase_				):
                  UpperCAmelCase          =       [files]
              UpperCAmelCase          =       [dl_manager.iter_files(lowercase_				) for file in files]
              splits.append(datasets.SplitGenerator(name=lowercase_ ,							gen_kwargs={'files': files}				)				)
          return splits




      def      a_   (				self ,							lowercase_				)    ->       pa.Table:
          if self.config.features is not None:
              # adding missing columns
              for column_name in set(self.config.features				) - set(pa_table.column_names				):
                  UpperCAmelCase          =       self.config.features.arrow_schema.field(lowercase_				).type
                  UpperCAmelCase          =       pa_table.append_column(lowercase_ ,							pa.array([None] * len(lowercase_				) ,							type=lowercase_				)				)
              # more expensive cast to support nested structures with keys in a different order
              # allows str <-> int/float or str to Audio for example
              UpperCAmelCase          =       table_cast(lowercase_ ,							self.config.features.arrow_schema				)
          return pa_table




      def      a_   (				self ,							lowercase_				)    ->       List[Any]:
          for file_idx, file in enumerate(itertools.chain.from_iterable(lowercase_				)				):
              # If the file is one json object and if we need to look at the list of items in one specific field
              if self.config.field is not None:
                  with open(lowercase_ ,							encoding=self.config.encoding ,							errors=self.config.encoding_errors				) as f:
                      UpperCAmelCase          =       json.load(lowercase_				)

                  # We keep only the field we are interested in
                  UpperCAmelCase          =       dataset[self.config.field]

                  # We accept two format: a list of dicts or a dict of lists
                  if isinstance(lowercase_ ,							(list, tuple)				):
                      UpperCAmelCase          =       set().union(*[row.keys() for row in dataset]				)
                      UpperCAmelCase          =       {col: [row.get(lowercase_				) for row in dataset] for col in keys}
                  else:
                      UpperCAmelCase          =       dataset
                  UpperCAmelCase          =       pa.Table.from_pydict(lowercase_				)
                  yield file_idx, self._cast_table(lowercase_				)

              # If the file has one json object per line
              else:
                  with open(lowercase_ ,							'rb'				) as f:
                      UpperCAmelCase          =       0
                      # Use block_size equal to the chunk size divided by 32 to leverage multithreading
                      # Set a default minimum value of 16kB if the chunk size is really small
                      UpperCAmelCase          =       max(self.config.chunksize // 3_2 ,							1_6 << 1_0				)
                      UpperCAmelCase          =       (
                          self.config.encoding_errors if self.config.encoding_errors is not None else 'strict'
                      )
                      while True:
                          UpperCAmelCase          =       f.read(self.config.chunksize				)
                          if not batch:
                              break
                          # Finish current line
                          try:
                              batch += f.readline()
                          except (AttributeError, io.UnsupportedOperation):
                              batch += readline(lowercase_				)
                          # PyArrow only accepts utf-8 encoded bytes
                          if self.config.encoding != "utf-8":
                              UpperCAmelCase          =       batch.decode(self.config.encoding ,							errors=lowercase_				).encode('utf-8'				)
                          try:
                              while True:
                                  try:
                                      UpperCAmelCase          =       paj.read_json(
                                          io.BytesIO(lowercase_				) ,							read_options=paj.ReadOptions(block_size=lowercase_				)				)
                                      break
                                  except (pa.ArrowInvalid, pa.ArrowNotImplementedError) as e:
                                      if (
                                          isinstance(lowercase_ ,							pa.ArrowInvalid				)
                                          and "straddling" not in str(lowercase_				)
                                          or block_size > len(lowercase_				)
                                      ):
                                          raise
                                      else:
                                          # Increase the block size in case it was too small.
                                          # The block size will be reset for the next file.
                                          logger.debug(
                                              F"Batch of {len(lowercase_				)} bytes couldn't be parsed with block_size={block_size}. Retrying with block_size={block_size * 2}."				)
                                          block_size *= 2
                          except pa.ArrowInvalid as e:
                              try:
                                  with open(
                                      lowercase_ ,							encoding=self.config.encoding ,							errors=self.config.encoding_errors				) as f:
                                      UpperCAmelCase          =       json.load(lowercase_				)
                              except json.JSONDecodeError:
                                  logger.error(F"Failed to read file '{file}' with error {type(lowercase_				)}: {e}"				)
                                  raise e
                              # If possible, parse the file as a list of json objects and exit the loop
                              if isinstance(lowercase_ ,							lowercase_				):  # list is the only sequence type supported in JSON
                                  try:
                                      UpperCAmelCase          =       set().union(*[row.keys() for row in dataset]				)
                                      UpperCAmelCase          =       {col: [row.get(lowercase_				) for row in dataset] for col in keys}
                                      UpperCAmelCase          =       pa.Table.from_pydict(lowercase_				)
                                  except (pa.ArrowInvalid, AttributeError) as e:
                                      logger.error(F"Failed to read file '{file}' with error {type(lowercase_				)}: {e}"				)
                                      raise ValueError(F"Not able to read records in the JSON file at {file}."				) from None
                                  yield file_idx, self._cast_table(lowercase_				)
                                  break
                              else:
                                  logger.error(F"Failed to read file '{file}' with error {type(lowercase_				)}: {e}"				)
                                  raise ValueError(
                                      F"Not able to read records in the JSON file at {file}. "
                                      F"You should probably indicate the field of the JSON file containing your records. "
                                      F"This JSON file contain the following fields: {str(list(dataset.keys()				)				)}. "
                                      F"Select the correct one and provide it as `field='XXX'` to the dataset loading method. "				) from None
                        # Uncomment for debugging (will print the Arrow table size and elements)
                        # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                        # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                          yield (file_idx, batch_idx), self._cast_table(lowercase_				)
                          batch_idx += 1





"""simple docstring"""

import logging
import os
import sys
import warnings
from dataclasses import dataclass, field
from random import randint
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import DatasetDict, load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoFeatureExtractor,
    AutoModelForAudioClassification,
    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


SCREAMING_SNAKE_CASE_            =    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.14.0''', '''To fix: pip install -r examples/pytorch/audio-classification/requirements.txt''')




def      lowercase__    (       lowerCAmelCase					:       np.ndarray			,					lowerCAmelCase					:       float			,					lowerCAmelCase					:       int = 16_000			)			->   List[Any]:






    """simple docstring"""




    UpperCAmelCase          =       int(round(sample_rate * max_length			)			)
    if len(lowerCAmelCase			) <= sample_length:
        return wav
    UpperCAmelCase          =       randint(0			,					len(lowerCAmelCase			) - sample_length - 1			)
    return wav[random_offset : random_offset + sample_length]
@dataclass
class   _UpperCAmelCase				:
      __SCREAMING_SNAKE_CASE :				Optional[str]				   =						field(default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "Name of a dataset from the datasets package"}				)
      __SCREAMING_SNAKE_CASE :				Optional[str]				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "The configuration name of the dataset to use (via the datasets library)."}				)
      __SCREAMING_SNAKE_CASE :				Optional[str]				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "A file containing the training audio paths and labels."}				)
      __SCREAMING_SNAKE_CASE :				Optional[str]				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "A file containing the validation audio paths and labels."}				)
      __SCREAMING_SNAKE_CASE :				str				   =						field(
          default="train"  ,      metadata={
              "help": "The name of the training data set split to use (via the datasets library). Defaults to 'train'"
          }  ,      )
      __SCREAMING_SNAKE_CASE :				str				   =						field(
          default="validation"  ,      metadata={
              "help": (
                  "The name of the training data set split to use (via the datasets library). Defaults to 'validation'"
              )
          }  ,      )
      __SCREAMING_SNAKE_CASE :				str				   =						field(
          default="audio"  ,      metadata={"help": "The name of the dataset column containing the audio data. Defaults to 'audio'"}  ,      )
      __SCREAMING_SNAKE_CASE :				str				   =						field(
          default="label"  ,      metadata={"help": "The name of the dataset column containing the labels. Defaults to 'label'"}				)
      __SCREAMING_SNAKE_CASE :				Optional[int]				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={
              "help": (
                  "For debugging purposes or quicker training, truncate the number of training examples to this "
                  "value if set."
              )
          }  ,      )
      __SCREAMING_SNAKE_CASE :				Optional[int]				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={
              "help": (
                  "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
                  "value if set."
              )
          }  ,      )
      __SCREAMING_SNAKE_CASE :				float				   =						field(
          default=2_0  ,      metadata={"help": "Audio clips will be randomly cut to this length during training if the value is set."}  ,      )

@dataclass
class   _UpperCAmelCase				:
      __SCREAMING_SNAKE_CASE :				str				   =						field(
          default="facebook/wav2vec2-base"  ,      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": "Where do you want to store the pretrained models downloaded from the Hub"}				)
      __SCREAMING_SNAKE_CASE :				str				   =						field(
          default="main"  ,      metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}  ,      )
      __SCREAMING_SNAKE_CASE :				Optional[str]				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "Name or path of preprocessor config."}				)
      __SCREAMING_SNAKE_CASE :				bool				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "Whether to freeze the feature encoder layers of the model."}				)
      __SCREAMING_SNAKE_CASE :				bool				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "Whether to generate an attention mask in the feature extractor."}				)
      __SCREAMING_SNAKE_CASE :				bool				   =						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)."
              )
          }  ,      )
      __SCREAMING_SNAKE_CASE :				Optional[bool]				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "Whether to freeze the feature extractor layers of the model."}				)
      __SCREAMING_SNAKE_CASE :				bool				   =						field(
          default=SCREAMING_SNAKE_CASE_  ,      metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."}  ,      )




      def      a_   (				self				)    ->       List[str]:
          if not self.freeze_feature_extractor and self.freeze_feature_encoder:
              warnings.warn(
                  'The argument `--freeze_feature_extractor` is deprecated and '
                  'will be removed in a future version. Use `--freeze_feature_encoder`'
                  'instead. Setting `freeze_feature_encoder==True`.' ,							lowercase_ ,							)
          if self.freeze_feature_extractor and not self.freeze_feature_encoder:
              raise ValueError(
                  'The argument `--freeze_feature_extractor` is deprecated and '
                  'should not be used in combination with `--freeze_feature_encoder`.'
                  'Only make use of `--freeze_feature_encoder`.'				)




def      lowercase__    (       )			->   List[Any]:






    """simple docstring"""




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

    # 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()

    UpperCAmelCase          =       training_args.get_process_log_level()
    logger.setLevel(lowerCAmelCase			)
    transformers.utils.logging.set_verbosity(lowerCAmelCase			)
    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}"			)

    # Set seed before initializing model.
    set_seed(training_args.seed			)

    # Detecting last checkpoint.
    UpperCAmelCase          =       None
    if os.path.isdir(training_args.output_dir			) and training_args.do_train and not training_args.overwrite_output_dir:
        UpperCAmelCase          =       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 train from scratch.'			)
        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.'			)

    # Initialize our dataset and prepare it for the audio classification task.
    UpperCAmelCase          =       DatasetDict()
    UpperCAmelCase          =       load_dataset(
        data_args.dataset_name			,					data_args.dataset_config_name			,					split=data_args.train_split_name			,					use_auth_token=True if model_args.use_auth_token else None			,					)
    UpperCAmelCase          =       load_dataset(
        data_args.dataset_name			,					data_args.dataset_config_name			,					split=data_args.eval_split_name			,					use_auth_token=True if model_args.use_auth_token else None			,					)

    if data_args.audio_column_name not in raw_datasets["train"].column_names:
        raise ValueError(
            F"--audio_column_name {data_args.audio_column_name} not found in dataset '{data_args.dataset_name}'. "
            'Make sure to set `--audio_column_name` to the correct audio column - one of '
            F"{', '.join(raw_datasets['train'].column_names			)}."			)

    if data_args.label_column_name not in raw_datasets["train"].column_names:
        raise ValueError(
            F"--label_column_name {data_args.label_column_name} not found in dataset '{data_args.dataset_name}'. "
            'Make sure to set `--label_column_name` to the correct text column - one of '
            F"{', '.join(raw_datasets['train'].column_names			)}."			)

    # Setting `return_attention_mask=True` is the way to get a correctly masked mean-pooling over
    # transformer outputs in the classifier, but it doesn't always lead to better accuracy
    UpperCAmelCase          =       AutoFeatureExtractor.from_pretrained(
        model_args.feature_extractor_name or model_args.model_name_or_path			,					return_attention_mask=model_args.attention_mask			,					cache_dir=model_args.cache_dir			,					revision=model_args.model_revision			,					use_auth_token=True if model_args.use_auth_token else None			,					)

    # `datasets` takes care of automatically loading and resampling the audio,
    # so we just need to set the correct target sampling rate.
    UpperCAmelCase          =       raw_datasets.cast_column(
        data_args.audio_column_name			,					datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate			)			)

    UpperCAmelCase          =       feature_extractor.model_input_names[0]

    def train_transforms(lowerCAmelCase					:       List[Any]			):
        UpperCAmelCase          =       []
        for audio in batch[data_args.audio_column_name]:
            UpperCAmelCase          =       random_subsample(
                audio['array']			,					max_length=data_args.max_length_seconds			,					sample_rate=feature_extractor.sampling_rate			)
            subsampled_wavs.append(lowerCAmelCase			)
        UpperCAmelCase          =       feature_extractor(lowerCAmelCase			,					sampling_rate=feature_extractor.sampling_rate			)
        UpperCAmelCase          =       {model_input_name: inputs.get(lowerCAmelCase			)}
        UpperCAmelCase          =       list(batch[data_args.label_column_name]			)

        return output_batch

    def val_transforms(lowerCAmelCase					:       int			):
        UpperCAmelCase          =       [audio['array'] for audio in batch[data_args.audio_column_name]]
        UpperCAmelCase          =       feature_extractor(lowerCAmelCase			,					sampling_rate=feature_extractor.sampling_rate			)
        UpperCAmelCase          =       {model_input_name: inputs.get(lowerCAmelCase			)}
        UpperCAmelCase          =       list(batch[data_args.label_column_name]			)

        return output_batch

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

    # Load the accuracy metric from the datasets package
    UpperCAmelCase          =       evaluate.load('accuracy'			)

    # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with
    # `predictions` and `label_ids` fields) and has to return a dictionary string to float.
    def compute_metrics(lowerCAmelCase					:       int			):
        UpperCAmelCase          =       np.argmax(eval_pred.predictions			,					axis=1			)
        return metric.compute(predictions=lowerCAmelCase			,					references=eval_pred.label_ids			)

    UpperCAmelCase          =       AutoConfig.from_pretrained(
        model_args.config_name or model_args.model_name_or_path			,					num_labels=len(lowerCAmelCase			)			,					labelaid=lowerCAmelCase			,					idalabel=lowerCAmelCase			,					finetuning_task='audio-classification'			,					cache_dir=model_args.cache_dir			,					revision=model_args.model_revision			,					use_auth_token=True if model_args.use_auth_token else None			,					)
    UpperCAmelCase          =       AutoModelForAudioClassification.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			,					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			,					)

    # freeze the convolutional waveform encoder
    if model_args.freeze_feature_encoder:
        model.freeze_feature_encoder()

    if training_args.do_train:
        if data_args.max_train_samples is not None:
            UpperCAmelCase          =       (
                raw_datasets['train'].shuffle(seed=training_args.seed			).select(range(data_args.max_train_samples			)			)
            )
        # Set the training transforms
        raw_datasets["train"].set_transform(lowerCAmelCase			,					output_all_columns=lowerCAmelCase			)

    if training_args.do_eval:
        if data_args.max_eval_samples is not None:
            UpperCAmelCase          =       (
                raw_datasets['eval'].shuffle(seed=training_args.seed			).select(range(data_args.max_eval_samples			)			)
            )
        # Set the validation transforms
        raw_datasets["eval"].set_transform(lowerCAmelCase			,					output_all_columns=lowerCAmelCase			)

    # Initialize our trainer
    UpperCAmelCase          =       Trainer(
        model=lowerCAmelCase			,					args=lowerCAmelCase			,					train_dataset=raw_datasets['train'] if training_args.do_train else None			,					eval_dataset=raw_datasets['eval'] if training_args.do_eval else None			,					compute_metrics=lowerCAmelCase			,					tokenizer=lowerCAmelCase			,					)

    # Training
    if training_args.do_train:
        UpperCAmelCase          =       None
        if training_args.resume_from_checkpoint is not None:
            UpperCAmelCase          =       training_args.resume_from_checkpoint
        elif last_checkpoint is not None:
            UpperCAmelCase          =       last_checkpoint
        UpperCAmelCase          =       trainer.train(resume_from_checkpoint=lowerCAmelCase			)
        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:
        UpperCAmelCase          =       trainer.evaluate()
        trainer.log_metrics('eval'			,					lowerCAmelCase			)
        trainer.save_metrics('eval'			,					lowerCAmelCase			)

    # Write model card and (optionally) push to hub
    UpperCAmelCase          =       {
        'finetuned_from': model_args.model_name_or_path,
        'tasks': 'audio-classification',
        'dataset': data_args.dataset_name,
        'tags': ['audio-classification'],
    }
    if training_args.push_to_hub:
        trainer.push_to_hub(**lowerCAmelCase			)
    else:
        trainer.create_model_card(**lowerCAmelCase			)


if __name__ == "__main__":
   main()



