
"""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


A_    							=					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__	,lowerCAmelCase__	,lowerCAmelCase__ = 16_000						):
			lowerCamelCase_					=  int(round(sample_rate * max_length						)						)
			if len(lowerCAmelCase__						) <= sample_length:
						return wav
			lowerCamelCase_					=  randint(0	,len(lowerCAmelCase__						) - sample_length - 1						)
			return wav[random_offset : random_offset + sample_length]




@dataclass
class  __lowerCamelCase  :
				a__:      Optional[str]          =    field(default=lowerCAmelCase						,	metadata={'help': 'Name of a dataset from the datasets package'}			)
				a__:      Optional[str]          =    field(
				    default=lowerCAmelCase						,	metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}			)
				a__:      Optional[str]          =    field(
				    default=lowerCAmelCase						,	metadata={'help': 'A file containing the training audio paths and labels.'}			)
				a__:      Optional[str]          =    field(
				    default=lowerCAmelCase						,	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=lowerCAmelCase						,	metadata={
				        'help': (
				            'For debugging purposes or quicker training, truncate the number of training examples to this '
				            'value if set.'
				        )
				    }						,	)
				a__:      Optional[int]          =    field(
				    default=lowerCAmelCase						,	metadata={
				        'help': (
				            'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
				            'value if set.'
				        )
				    }						,	)
				a__:      float          =    field(
				    default=20						,	metadata={'help': 'Audio clips will be randomly cut to this length during training if the value is set.'}						,	)




@dataclass
class  __lowerCamelCase  :
				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=lowerCAmelCase						,	metadata={'help': 'Pretrained config name or path if not the same as model_name'}			)
				a__:      Optional[str]          =    field(
				    default=lowerCAmelCase						,	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=lowerCAmelCase						,	metadata={'help': 'Name or path of preprocessor config.'}			)
				a__:      bool          =    field(
				    default=lowerCAmelCase						,	metadata={'help': 'Whether to freeze the feature encoder layers of the model.'}			)
				a__:      bool          =    field(
				    default=lowerCAmelCase						,	metadata={'help': 'Whether to generate an attention mask in the feature extractor.'}			)
				a__:      bool          =    field(
				    default=lowerCAmelCase						,	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=lowerCAmelCase						,	metadata={'help': 'Whether to freeze the feature extractor layers of the model.'}			)
				a__:      bool          =    field(
				    default=lowerCAmelCase						,	metadata={'help': 'Will enable to load a pretrained model whose head dimensions are different.'}						,	)




				def        UpperCAmelCase__						(				self   ):
							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`.'''							,						UpperCAmelCase							,						)
							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						(	):
			# 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_					=  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_					=  parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
			else:
						lowerCamelCase_		, lowerCamelCase_		, lowerCamelCase_					=  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_					=  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_					=  None
			if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
						lowerCamelCase_					=  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_					=  DatasetDict()
			lowerCamelCase_					=  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_					=  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_					=  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_					=  raw_datasets.cast_column(
			    data_args.audio_column_name	,datasets.features.Audio(sampling_rate=feature_extractor.sampling_rate						)						)

			lowerCamelCase_					=  feature_extractor.model_input_names[0]

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

						return output_batch

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

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

			lowerCamelCase_					=  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_					=  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_					=  (
									    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_					=  (
									    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_					=  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_					=  None
						if training_args.resume_from_checkpoint is not None:
									lowerCamelCase_					=  training_args.resume_from_checkpoint
						elif last_checkpoint is not None:
									lowerCamelCase_					=  last_checkpoint
						lowerCamelCase_					=  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_					=  trainer.evaluate()
						trainer.log_metrics('''eval'''	,lowerCAmelCase__						)
						trainer.save_metrics('''eval'''	,lowerCAmelCase__						)

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





import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
							import torch

							from transformers.generation import DisjunctiveConstraint

@require_torch
class 							_UpperCamelCase					(       unittest.TestCase	):






			'''simple docstring'''

			def    lowerCAmelCase__						(							self			:							Dict   ):
							# For consistency across different places the DisjunctiveConstraint is called,
							# dc.token_ids is a list of integers. It is also initialized only by integers.

							UpperCamelCase_:				Optional[int]						=    [[1, 2, 4], [1, 2, 3, 4]]
							UpperCamelCase_:				List[str]						=    DisjunctiveConstraint(snake_case_   )
							self.assertTrue(isinstance(dc.token_ids    ,						snake_case_   )   )

							with self.assertRaises(snake_case_   ):
											DisjunctiveConstraint(torch.LongTensor([[1, 2, 4], [1, 2, 3]]   )   )

							with self.assertRaises(snake_case_   ):
											DisjunctiveConstraint([torch.LongTensor([1, 2, 4]   ), torch.LongTensor([1, 2, 3, 4, 5]   )]   )

			def    lowerCAmelCase__						(							self			:							Optional[Any]   ):
							# We can't have constraints that are complete subsets of another. This leads to a preverse
							# interpretation of "constraint fulfillment": does generating [1,2,3] fulfill the constraint?
							# It would mean that it generated [1,2] which fulfills it, but it's in the middle of potentially
							# fulfilling [1,2,3,4]. If we believe that [1,2,3] does fulfill the constraint, then the algorithm
							# will necessarily never reach [1,2,3,4], giving users a false sense of control (better to just not allow it).
							UpperCamelCase_:				Dict						=    [[1, 2], [1, 2, 3, 4]]

							with self.assertRaises(snake_case_   ):
											DisjunctiveConstraint(snake_case_   )  # fails here

			def    lowerCAmelCase__						(							self			:							int   ):
							UpperCamelCase_:				Dict						=    [[1, 2, 3], [1, 2, 4]]

							UpperCamelCase_:				Dict						=    DisjunctiveConstraint(snake_case_   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				str						=    dc.update(1   )
							UpperCamelCase_:				Union[str, Any]						=    stepped is True and completed is False and reset is False
							self.assertTrue(snake_case_   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Optional[int]						=    dc.update(2   )
							UpperCamelCase_:				Tuple						=    stepped is True and completed is False and reset is False
							self.assertTrue(snake_case_   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1, 2]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Optional[int]						=    dc.update(3   )
							UpperCamelCase_:				Union[str, Any]						=    stepped is True and completed is True and reset is False
							self.assertTrue(snake_case_   )
							self.assertTrue(dc.completed   )  # Completed!
							self.assertTrue(dc.current_seq == [1, 2, 3]   )




			def    lowerCAmelCase__						(							self			:							List[str]   ):
							UpperCamelCase_:				Optional[int]						=    [[1, 2, 3], [1, 2, 4, 5], [1, 2, 5]]

							UpperCamelCase_:				Tuple						=    DisjunctiveConstraint(snake_case_   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Dict						=    dc.update(1   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Union[str, Any]						=    dc.update(2   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1, 2]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Any						=    dc.update(4   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.current_seq == [1, 2, 4]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				int						=    dc.update(5   )
							self.assertTrue(dc.completed   )  # Completed!
							self.assertTrue(dc.current_seq == [1, 2, 4, 5]   )

							dc.reset()

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				int						=    dc.update(1   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.remaining() == 3   )
							self.assertTrue(dc.current_seq == [1]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				Tuple						=    dc.update(2   )
							self.assertTrue(not dc.completed   )
							self.assertTrue(dc.remaining() == 2   )
							self.assertTrue(dc.current_seq == [1, 2]   )

							UpperCamelCase_, UpperCamelCase_, UpperCamelCase_:				List[str]						=    dc.update(5   )
							self.assertTrue(dc.completed   )  # Completed!
							self.assertTrue(dc.remaining() == 0   )
							self.assertTrue(dc.current_seq == [1, 2, 5]   )






