





import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


_lowercase		:  Optional[int]			       =logging.getLogger(__name__)


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






@dataclass
class 						UpperCamelCase_  :
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={
					        'help': (
					            'The model checkpoint for weights initialization. Leave None if you want to train a model from'
					            ' scratch.'
					        )
					    }  ,     )
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'If training from scratch, pass a model type from the list: ' + ', '.join(snake_case__							)}  ,     )
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Pretrained config name or path if not the same as model_name'}							)
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'}							)
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}  ,     )






@dataclass
class 						UpperCamelCase_  :
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'The input training data file (a text file).'}							)
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={
					        'help': (
					            'The input training data files (multiple files in glob format). '
					            'Very often splitting large files to smaller files can prevent tokenizer going out of memory'
					        )
					    }  ,     )
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'An optional input evaluation data file to evaluate the perplexity on (a text file).'}  ,     )
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'An optional input train ref data file for whole word mask in Chinese.'}  ,     )
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'An optional input eval ref data file for whole word mask in Chinese.'}  ,     )
					_a      :						bool						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Whether distinct lines of text in the dataset are to be handled as distinct sequences.'}  ,     )

					_a      :						bool						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Train with masked-language modeling loss instead of language modeling.'}							)
					_a      :						bool						    =					field(default=snake_case__  ,     metadata={'help': 'Whether ot not to use whole word mask.'}							)
					_a      :						float						    =					field(
					    default=0.15  ,     metadata={'help': 'Ratio of tokens to mask for masked language modeling loss'}							)
					_a      :						float						    =					field(
					    default=1 / 6  ,     metadata={
					        'help': (
					            'Ratio of length of a span of masked tokens to surrounding context length for permutation language'
					            ' modeling.'
					        )
					    }  ,     )
					_a      :						int						    =					field(
					    default=5  ,     metadata={'help': 'Maximum length of a span of masked tokens for permutation language modeling.'}							)

					_a      :						int						    =					field(
					    default=-1  ,     metadata={
					        'help': (
					            'Optional input sequence length after tokenization.'
					            'The training dataset will be truncated in block of this size for training.'
					            'Default to the model max input length for single sentence inputs (take into account special tokens).'
					        )
					    }  ,     )
					_a      :						bool						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Overwrite the cached training and evaluation sets'}							)


def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__ = False							,lowerCAmelCase__ = None							,):
		def _dataset(lowerCAmelCase__							,lowerCAmelCase__=None						):
				if args.line_by_line:
						if ref_path is not None:
								if not args.whole_word_mask or not args.mlm:
										raise ValueError('You need to set world whole masking and mlm to True for Chinese Whole Word Mask'						)
								return LineByLineWithRefDataset(
								    tokenizer=lowerCAmelCase__							,file_path=lowerCAmelCase__							,block_size=args.block_size							,ref_path=lowerCAmelCase__							,)

						return LineByLineTextDataset(tokenizer=lowerCAmelCase__							,file_path=lowerCAmelCase__							,block_size=args.block_size						)
				else:
						return TextDataset(
						    tokenizer=lowerCAmelCase__							,file_path=lowerCAmelCase__							,block_size=args.block_size							,overwrite_cache=args.overwrite_cache							,cache_dir=lowerCAmelCase__							,)

		if evaluate:
				return _dataset(args.eval_data_file							,args.eval_ref_file						)
		elif args.train_data_files:
				return ConcatDataset([_dataset(lowerCAmelCase__						) for f in glob(args.train_data_files						)]						)
		else:
				return _dataset(args.train_data_file							,args.train_ref_file						)


def 		_SCREAMING_SNAKE_CASE     ( ):
		# 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.

		lowerCamelCase_	:     Optional[int] 						=      HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
		lowerCamelCase_						,      lowerCamelCase_						,      lowerCamelCase_	:     Optional[int] 						=      parser.parse_args_into_dataclasses()

		if data_args.eval_data_file is None and training_args.do_eval:
				raise ValueError(
				    'Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file '
				    'or remove the --do_eval argument.'						)
		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						)

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

		if model_args.config_name:
				lowerCamelCase_	:     List[Any] 						=      AutoConfig.from_pretrained(model_args.config_name							,cache_dir=model_args.cache_dir						)
		elif model_args.model_name_or_path:
				lowerCamelCase_	:     Optional[Any] 						=      AutoConfig.from_pretrained(model_args.model_name_or_path							,cache_dir=model_args.cache_dir						)
		else:
				lowerCamelCase_	:     Union[str, Any] 						=      CONFIG_MAPPING[model_args.model_type]()
				logger.warning('You are instantiating a new config instance from scratch.'						)

		if model_args.tokenizer_name:
				lowerCamelCase_	:     int 						=      AutoTokenizer.from_pretrained(model_args.tokenizer_name							,cache_dir=model_args.cache_dir						)
		elif model_args.model_name_or_path:
				lowerCamelCase_	:     Union[str, Any] 						=      AutoTokenizer.from_pretrained(model_args.model_name_or_path							,cache_dir=model_args.cache_dir						)
		else:
				raise ValueError(
				    'You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another'
				    ' script, save it,and load it from here, using --tokenizer_name'						)

		if model_args.model_name_or_path:
				lowerCamelCase_	:     Optional[Any] 						=      AutoModelWithLMHead.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							,)
		else:
				logger.info('Training new model from scratch'						)
				lowerCamelCase_	:     int 						=      AutoModelWithLMHead.from_config(lowerCAmelCase__						)

		model.resize_token_embeddings(len(lowerCAmelCase__						)						)

		if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
				raise ValueError(
				    'BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the'
				    '--mlm flag (masked language modeling).'						)

		if data_args.block_size <= 0:
				lowerCamelCase_	:     int 						=      tokenizer.max_len
				# Our input block size will be the max possible for the model
		else:
				lowerCamelCase_	:     int 						=      min(data_args.block_size							,tokenizer.max_len						)

		# Get datasets

		lowerCamelCase_	:     int 						=      (
		    get_dataset(lowerCAmelCase__							,tokenizer=lowerCAmelCase__							,cache_dir=model_args.cache_dir						) if training_args.do_train else None
		)
		lowerCamelCase_	:     List[Any] 						=      (
		    get_dataset(lowerCAmelCase__							,tokenizer=lowerCAmelCase__							,evaluate=lowerCAmelCase__							,cache_dir=model_args.cache_dir						)
		    if training_args.do_eval
		    else None
		)
		if config.model_type == "xlnet":
				lowerCamelCase_	:     Tuple 						=      DataCollatorForPermutationLanguageModeling(
				    tokenizer=lowerCAmelCase__							,plm_probability=data_args.plm_probability							,max_span_length=data_args.max_span_length							,)
		else:
				if data_args.mlm and data_args.whole_word_mask:
						lowerCamelCase_	:     int 						=      DataCollatorForWholeWordMask(
						    tokenizer=lowerCAmelCase__							,mlm_probability=data_args.mlm_probability						)
				else:
						lowerCamelCase_	:     Any 						=      DataCollatorForLanguageModeling(
						    tokenizer=lowerCAmelCase__							,mlm=data_args.mlm							,mlm_probability=data_args.mlm_probability						)

    # Initialize our Trainer
		lowerCamelCase_	:     Any 						=      Trainer(
		    model=lowerCAmelCase__							,args=lowerCAmelCase__							,data_collator=lowerCAmelCase__							,train_dataset=lowerCAmelCase__							,eval_dataset=lowerCAmelCase__							,prediction_loss_only=lowerCAmelCase__							,)

		# Training
		if training_args.do_train:
				lowerCamelCase_	:     List[str] 						=      (
				    model_args.model_name_or_path
				    if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path						)
				    else None
				)
				trainer.train(model_path=lowerCAmelCase__						)
				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
		lowerCamelCase_	:     Optional[Any] 						=      {}
		if training_args.do_eval:
				logger.info('*** Evaluate ***'						)

				lowerCamelCase_	:     List[str] 						=      trainer.evaluate()

				lowerCamelCase_	:     Any 						=      math.exp(eval_output['eval_loss']						)
				lowerCamelCase_	:     Any 						=      {'perplexity': perplexity}

				lowerCamelCase_	:     Any 						=      os.path.join(training_args.output_dir							,'eval_results_lm.txt'						)
				if trainer.is_world_master():
						with open(lowerCAmelCase__							,'w'						) as writer:
								logger.info('***** Eval results *****'						)
								for key in sorted(result.keys()						):
										logger.info('  %s = %s'							,lowerCAmelCase__							,str(result[key]						)						)
										writer.write('%s = %s\n' % (key, str(result[key]						))						)

				results.update(lowerCAmelCase__						)

		return results


def 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__						):
		# For xla_spawn (TPUs)
		main()


if __name__ == "__main__":
		main()







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


_lowercase		:  Union[str, Any]			       =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 		_SCREAMING_SNAKE_CASE     ( lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__ = 1_60_00						):
		lowerCamelCase_	:     List[str] 						=      int(round(sample_rate * max_length						)						)
		if len(lowerCAmelCase__						) <= sample_length:
				return wav
		lowerCamelCase_	:     int 						=      randint(0							,len(lowerCAmelCase__						) - sample_length - 1						)
		return wav[random_offset : random_offset + sample_length]






@dataclass
class 						UpperCamelCase_  :
					_a      :						Optional[str]						    =					field(default=snake_case__  ,     metadata={'help': 'Name of a dataset from the datasets package'}							)
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}							)
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'A file containing the training audio paths and labels.'}							)
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'A file containing the validation audio paths and labels.'}							)
					_a      :						str						    =					field(
					    default='train'  ,     metadata={
					        'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
					    }  ,     )
					_a      :						str						    =					field(
					    default='validation'  ,     metadata={
					        'help': (
					            'The name of the training data set split to use (via the datasets library). Defaults to \'validation\''
					        )
					    }  ,     )
					_a      :						str						    =					field(
					    default='audio'  ,     metadata={'help': 'The name of the dataset column containing the audio data. Defaults to \'audio\''}  ,     )
					_a      :						str						    =					field(
					    default='label'  ,     metadata={'help': 'The name of the dataset column containing the labels. Defaults to \'label\''}							)
					_a      :						Optional[int]						    =					field(
					    default=snake_case__  ,     metadata={
					        'help': (
					            'For debugging purposes or quicker training, truncate the number of training examples to this '
					            'value if set.'
					        )
					    }  ,     )
					_a      :						Optional[int]						    =					field(
					    default=snake_case__  ,     metadata={
					        'help': (
					            'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
					            'value if set.'
					        )
					    }  ,     )
					_a      :						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_  :
					_a      :						str						    =					field(
					    default='facebook/wav2vec2-base'  ,     metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}  ,     )
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Pretrained config name or path if not the same as model_name'}							)
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Where do you want to store the pretrained models downloaded from the Hub'}							)
					_a      :						str						    =					field(
					    default='main'  ,     metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}  ,     )
					_a      :						Optional[str]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Name or path of preprocessor config.'}							)
					_a      :						bool						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Whether to freeze the feature encoder layers of the model.'}							)
					_a      :						bool						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Whether to generate an attention mask in the feature extractor.'}							)
					_a      :						bool						    =					field(
					    default=snake_case__  ,     metadata={
					        'help': (
					            'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
					            'with private models).'
					        )
					    }  ,     )
					_a      :						Optional[bool]						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Whether to freeze the feature extractor layers of the model.'}							)
					_a      :						bool						    =					field(
					    default=snake_case__  ,     metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'}  ,     )



					def   __a     (		self     :     Optional[int]						):
							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`.'       ,      lowerCamelCase       ,      )
							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 		_SCREAMING_SNAKE_CASE     ( ):
		# 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.

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

		lowerCamelCase_	:     List[str] 						=      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.
		lowerCamelCase_	:     Union[str, Any] 						=      None
		if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
				lowerCamelCase_	:     Optional[Any] 						=      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.
		lowerCamelCase_	:     Optional[int] 						=      DatasetDict()
		lowerCamelCase_	:     Dict 						=      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							,)
		lowerCamelCase_	:     List[str] 						=      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
		lowerCamelCase_	:     Dict 						=      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.
		lowerCamelCase_	:     Optional[Any] 						=      raw_datasets.cast_column(
		    data_args.audio_column_name							,datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate						)						)

		lowerCamelCase_	:     Optional[int] 						=      feature_extractor.model_input_names[0]

		def train_transforms(lowerCAmelCase__						):
				lowerCamelCase_	:     Optional[int] 						=      []
				for audio in batch[data_args.audio_column_name]:
						lowerCamelCase_	:     Union[str, Any] 						=      random_subsample(
						    audio['array']							,max_length=data_args.max_length_seconds							,sample_rate=feature_extractor.sampling_rate						)
						subsampled_wavs.append(lowerCAmelCase__						)
				lowerCamelCase_	:     int 						=      feature_extractor(lowerCAmelCase__							,sampling_rate=feature_extractor.sampling_rate						)
				lowerCamelCase_	:     Optional[Any] 						=      {model_input_name: inputs.get(lowerCAmelCase__						)}
				lowerCamelCase_	:     Any 						=      list(batch[data_args.label_column_name]						)

				return output_batch

		def val_transforms(lowerCAmelCase__						):
				lowerCamelCase_	:     Dict 						=      [audio['array'] for audio in batch[data_args.audio_column_name]]
				lowerCamelCase_	:     Optional[Any] 						=      feature_extractor(lowerCAmelCase__							,sampling_rate=feature_extractor.sampling_rate						)
				lowerCamelCase_	:     Optional[int] 						=      {model_input_name: inputs.get(lowerCAmelCase__						)}
				lowerCamelCase_	:     Tuple 						=      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.
		lowerCamelCase_	:     Optional[int] 						=      raw_datasets['train'].features[data_args.label_column_name].names
		lowerCamelCase_						,      lowerCamelCase_	:     Optional[int] 						=      {}, {}
		for i, label in enumerate(lowerCAmelCase__						):
				lowerCamelCase_	:     List[Any] 						=      str(lowerCAmelCase__						)
				lowerCamelCase_	:     Union[str, Any] 						=      label

		# Load the accuracy metric from the datasets package
		lowerCamelCase_	:     Tuple 						=      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__						):
				lowerCamelCase_	:     Tuple 						=      np.argmax(eval_pred.predictions							,axis=1						)
				return metric.compute(predictions=lowerCAmelCase__							,references=eval_pred.label_ids						)

		lowerCamelCase_	:     Union[str, Any] 						=      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							,)
		lowerCamelCase_	:     Optional[int] 						=      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:
						lowerCamelCase_	:     List[Any] 						=      (
						    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:
						lowerCamelCase_	:     List[str] 						=      (
						    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
		lowerCamelCase_	:     str 						=      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:
				lowerCamelCase_	:     List[Any] 						=      None
				if training_args.resume_from_checkpoint is not None:
						lowerCamelCase_	:     List[Any] 						=      training_args.resume_from_checkpoint
				elif last_checkpoint is not None:
						lowerCamelCase_	:     Dict 						=      last_checkpoint
				lowerCamelCase_	:     Optional[int] 						=      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:
				lowerCamelCase_	:     str 						=      trainer.evaluate()
				trainer.log_metrics('eval'							,lowerCAmelCase__						)
				trainer.save_metrics('eval'							,lowerCAmelCase__						)

		# Write model card and (optionally) push to hub
		lowerCamelCase_	:     List[Any] 						=      {
		    '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()
